File tree 1 file changed +59
-0
lines changed
1 file changed +59
-0
lines changed Original file line number Diff line number Diff line change
1
+ class Solution {
2
+ public:
3
+ void reorderList(ListNode* head) {
4
+ if (!head || !head->next) {
5
+ return;
6
+ }
7
+
8
+ ListNode* middle = midNode(head);
9
+ ListNode* newHead = middle->next;
10
+ middle->next = nullptr;
11
+
12
+ newHead = reverseLinkedList(newHead);
13
+
14
+ ListNode* c1 = head;
15
+ ListNode* c2 = newHead;
16
+ ListNode* f1 = nullptr;
17
+ ListNode* f2 = nullptr;
18
+
19
+ while (c1 && c2) {
20
+ // Backup
21
+ f1 = c1->next;
22
+ f2 = c2->next;
23
+
24
+ // Linking
25
+ c1->next = c2;
26
+ c2->next = f1;
27
+
28
+ // Move
29
+ c1 = f1;
30
+ c2 = f2;
31
+ }
32
+ }
33
+
34
+ private:
35
+ ListNode* midNode(ListNode* head) {
36
+ ListNode* slow = head;
37
+ ListNode* fast = head;
38
+
39
+ while (fast->next && fast->next->next) {
40
+ slow = slow->next;
41
+ fast = fast->next->next;
42
+ }
43
+ return slow;
44
+ }
45
+
46
+ ListNode* reverseLinkedList(ListNode* head) {
47
+ ListNode* prev = nullptr;
48
+ ListNode* curr = head;
49
+ ListNode* forw = nullptr;
50
+
51
+ while (curr) {
52
+ forw = curr->next;
53
+ curr->next = prev;
54
+ prev = curr;
55
+ curr = forw;
56
+ }
57
+ return prev;
58
+ }
59
+ };
You can’t perform that action at this time.
0 commit comments