[InterviewBit] Reorder List

Reorder List

  • Time : O(n)
  • Space : O(1)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
ListNode* reverse(ListNode* A) {
ListNode* dummy = new ListNode(-1);
ListNode* runner = A;
while(runner) {
ListNode* next = runner->next;
runner->next = dummy->next;
dummy->next = runner;
runner = next;
}
return dummy->next;
}

ListNode* Solution::reorderList(ListNode* A) {
if(A->next == NULL or A->next->next == NULL) return A;

ListNode* slow = A;
ListNode* fast = A;
while(fast->next and fast->next->next) {
slow = slow->next;
fast = fast->next->next;
}
ListNode* back = slow->next;
slow->next = NULL;
ListNode* rev = reverse(back);
ListNode* dummy = new ListNode(-1);
ListNode* runner = dummy;

while(A and rev) {
if(A) {
runner->next = A;
A = A->next;
runner = runner->next;
runner->next = NULL;
}
if(rev) {
runner->next = rev;
rev = rev->next;
runner = runner->next;
runner->next = NULL;
}
}
if(A) {
runner->next = A;
A = A->next;
runner = runner->next;
runner->next = NULL;
}

return dummy->next;
}

Author: Song Hayoung
Link: https://songhayoung.github.io/2022/08/30/PS/interviewbit/reorder-list/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.