Skip to content

Commit 933ca4a

Browse files
authored
Merge pull request neetcode-gh#21 from bryanhitc/brhitchc/cpp-143-reorder-list
[C++] 143: Reorder List
2 parents a5a962f + 9f031be commit 933ca4a

File tree

1 file changed

+72
-0
lines changed

1 file changed

+72
-0
lines changed

cpp/143-Reorder-List.cpp

Lines changed: 72 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,72 @@
1+
/**
2+
* Definition for singly-linked list.
3+
* struct ListNode {
4+
* int val;
5+
* ListNode *next;
6+
* ListNode() : val(0), next(nullptr) {}
7+
* ListNode(int x) : val(x), next(nullptr) {}
8+
* ListNode(int x, ListNode *next) : val(x), next(next) {}
9+
* };
10+
*/
11+
class Solution {
12+
public:
13+
void reorderList(ListNode* head) {
14+
ListNode* prev = nullptr;
15+
ListNode* slow = head;
16+
ListNode* fast = head;
17+
18+
// set slow to middle node
19+
while (fast != nullptr && fast->next != nullptr) {
20+
prev = slow;
21+
slow = slow->next;
22+
fast = fast->next->next;
23+
}
24+
25+
if (prev != nullptr) {
26+
prev->next = reverseList(slow);
27+
mergeTwoLists(head, prev->next);
28+
}
29+
}
30+
31+
private:
32+
ListNode* reverseList(ListNode* head) {
33+
ListNode* prev = nullptr;
34+
ListNode* curr = head;
35+
36+
while (curr != nullptr) {
37+
ListNode* next = curr->next;
38+
curr->next = prev;
39+
prev = curr;
40+
curr = next;
41+
}
42+
43+
return prev;
44+
}
45+
46+
// invariant: list2 length = [list1 length, list1 length + 1]
47+
ListNode* mergeTwoLists(ListNode* list1, ListNode* list2) {
48+
ListNode dummy;
49+
ListNode* prev = &dummy;
50+
51+
ListNode* l1 = list1;
52+
ListNode* l2 = list2;
53+
54+
while (l1 != list2) {
55+
takeNode(prev, l1);
56+
takeNode(prev, l2);
57+
}
58+
59+
// handle odd number of nodes
60+
if (l2 != nullptr) {
61+
takeNode(prev, l2);
62+
}
63+
64+
return dummy.next;
65+
}
66+
67+
void takeNode(ListNode*& prev, ListNode*& curr) {
68+
prev->next = curr;
69+
prev = prev->next;
70+
curr = curr->next;
71+
}
72+
};

0 commit comments

Comments
 (0)