@@ -32,7 +32,7 @@ class Solution {
32
32
*
33
33
* Source: https://www.kancloud.cn/kancloud/data-structure-and-algorithm-notes/73015
34
34
*/
35
- void reorderList (ListNode* head) {
35
+ void reorderList1 (ListNode* head) {
36
36
if (head == NULL || head->next == NULL || head->next ->next == NULL ) {
37
37
return ;
38
38
}
@@ -60,6 +60,58 @@ class Solution {
60
60
last = temp;
61
61
}
62
62
}
63
+
64
+ void reorderList2 (ListNode* head) {
65
+ if (head == NULL || head->next == NULL || head->next ->next ) return ;
66
+
67
+ ListNode* middle = findMiddle (head);
68
+ ListNode* right = reverse (middle->next );
69
+ middle->next = NULL ;
70
+
71
+ merge (head, right);
72
+ }
73
+
74
+ void merge (ListNode* left, ListNode* right) {
75
+ ListNode* dummy = new ListNode (0 );
76
+
77
+ while (left != NULL && right != NULL ){
78
+ dummy->next = left;
79
+ left = left->next ;
80
+ dummy = dummy->next ;
81
+ dummy->next = right;
82
+ right = right->next ;
83
+ dummy = dummy->next ;
84
+ }
85
+
86
+ dummy->next = left != NULL ? left : right;
87
+ }
88
+
89
+ ListNode* reverse (ListNode* head) {
90
+ ListNode* newHead = NULL ;
91
+
92
+ while (head != NULL ){
93
+ ListNode* temp = head->next ;
94
+ head->next = newHead;
95
+ newHead = head;
96
+ head = temp;
97
+ }
98
+
99
+ return newHead;
100
+ }
101
+
102
+ ListNode* findMiddle (ListNode* head) {
103
+ if (head == NULL || head->next == NULL ) {
104
+ return head;
105
+ }
106
+
107
+ ListNode *slow = head, *fast = head->next ;
108
+ while (slow != NULL && fast != NULL ) {
109
+ slow = slow->next ;
110
+ fast = fast->next ->next ;
111
+ }
112
+
113
+ return slow;
114
+ }
63
115
};
64
116
65
117
/* Function to print nodes in a given linked list */
@@ -78,7 +130,7 @@ int main() {
78
130
head->next ->next ->next ->next = new ListNode (5 );
79
131
head->next ->next ->next ->next ->next = new ListNode (6 );
80
132
81
- Solution ().reorderList (head);
133
+ Solution ().reorderList2 (head);
82
134
printList (head);
83
135
84
136
return 0 ;
0 commit comments