File tree Expand file tree Collapse file tree 1 file changed +73
-0
lines changed Expand file tree Collapse file tree 1 file changed +73
-0
lines changed Original file line number Diff line number Diff line change
1
+ // space O(n)
2
+ class Solution {
3
+ public:
4
+ void reorderList (ListNode* head) {
5
+ ListNode* search = head->next ;
6
+ ListNode* tail = head;
7
+ deque<ListNode*> q;
8
+
9
+ while (search){
10
+ ListNode* next = search->next ;
11
+
12
+ search->next = NULL ;
13
+ q.push_back (search);
14
+ search = next;
15
+ }
16
+
17
+ for (int i = 0 ; !q.empty (); i++){
18
+ if (i % 2 == 0 ){
19
+ tail->next = q.back ();
20
+ q.pop_back ();
21
+ }else {
22
+ tail->next = q.front ();
23
+ q.pop_front ();
24
+ }
25
+
26
+ tail = tail->next ;
27
+ }
28
+ }
29
+ };
30
+
31
+
32
+ // space O(1)
33
+ class Solution {
34
+ public:
35
+ void reorderList (ListNode* head) {
36
+ if (head == NULL || head->next == NULL )
37
+ return ;
38
+
39
+ ListNode* slow = head;
40
+ ListNode* fast = head;
41
+
42
+ while (fast->next && fast->next ->next ){
43
+ slow = slow->next ;
44
+ fast = fast->next ->next ;
45
+ }
46
+
47
+ ListNode* prev = nullptr ;
48
+ ListNode* curr = slow->next ;
49
+
50
+ while (curr){
51
+ ListNode* next = curr->next ;
52
+ curr->next = prev;
53
+ prev = curr;
54
+ curr = next;
55
+ }
56
+
57
+ slow->next = nullptr ;
58
+
59
+ ListNode* first = head;
60
+ ListNode* second = prev;
61
+
62
+ while (first && second){
63
+ ListNode* next1 = first->next ;
64
+ ListNode* next2 = second->next ;
65
+
66
+ first->next = second;
67
+ second->next = next1;
68
+
69
+ first = next1;
70
+ second = next2;
71
+ }
72
+ }
73
+ };
You can’t perform that action at this time.
0 commit comments