Skip to content

Commit 4739fc5

Browse files
committed
Update and rename reorderList.cpp to reorder-list.cpp
1 parent e7cd8df commit 4739fc5

File tree

2 files changed

+70
-69
lines changed

2 files changed

+70
-69
lines changed

C++/reorder-list.cpp

+70
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,70 @@
1+
// Time: O(n)
2+
// Space: O(1)
3+
4+
/**
5+
* Definition for singly-linked list.
6+
* struct ListNode {
7+
* int val;
8+
* ListNode *next;
9+
* ListNode(int x) : val(x), next(NULL) {}
10+
* };
11+
*/
12+
class Solution {
13+
public:
14+
void reorderList(ListNode *head) {
15+
if (!head) {
16+
return;
17+
}
18+
19+
auto slow = head, fast = head;
20+
21+
while (fast->next && fast->next->next) {
22+
slow = slow->next;
23+
fast = fast->next->next;
24+
}
25+
26+
// Split into two lists.
27+
auto tmp = slow->next;
28+
slow->next = nullptr;
29+
slow = tmp;
30+
31+
merge(head, reverse(slow));
32+
}
33+
34+
private:
35+
ListNode *reverse(ListNode *head) {
36+
ListNode dummy{0};
37+
38+
while (head) {
39+
auto tmp = head->next;
40+
head->next = dummy.next;
41+
dummy.next = head;
42+
head = tmp;
43+
}
44+
45+
return dummy.next;
46+
}
47+
48+
ListNode *merge(ListNode *list1, ListNode *list2) {
49+
ListNode dummy{0};
50+
auto ptr = &dummy;
51+
52+
while (list1 && list2) {
53+
auto tmp = list1->next;
54+
55+
ptr->next = list1;
56+
ptr = ptr->next;
57+
ptr->next = list2;
58+
ptr = ptr->next;
59+
60+
list1 = tmp;
61+
list2 = list2->next;
62+
}
63+
64+
if (list1) {
65+
ptr->next = list1;
66+
}
67+
68+
return dummy.next;
69+
}
70+
};

C++/reorderList.cpp

-69
This file was deleted.

0 commit comments

Comments
 (0)