@@ -29,6 +29,8 @@ class Solution {
29
29
*
30
30
* Example:
31
31
* Given 1->2->3->4->null, reorder it to 1->4->2->3->null.
32
+ *
33
+ * Source: https://www.kancloud.cn/kancloud/data-structure-and-algorithm-notes/73015
32
34
*/
33
35
void reorderList (ListNode* head) {
34
36
if (head == NULL || head->next == NULL || head->next ->next == NULL ) {
@@ -41,10 +43,43 @@ class Solution {
41
43
last = last->next ;
42
44
++length;
43
45
}
44
-
46
+
47
+ last = head;
48
+
49
+ for (int i = 1 ; i < length - i; ++i) {
50
+ ListNode* beforeTail = last;
51
+
52
+ for (int j = i; j < length - i; ++j) {
53
+ beforeTail = beforeTail->next ;
54
+ }
55
+
56
+ ListNode* temp = last->next ;
57
+ last->next = beforeTail->next ;
58
+ last->next ->next = temp;
59
+ beforeTail->next = NULL ;
60
+ last = temp;
61
+ }
45
62
}
46
63
};
47
64
65
+ /* Function to print nodes in a given linked list */
66
+ void printList (ListNode *node) {
67
+ while (node != NULL ) {
68
+ printf (" %d " , node->val );
69
+ node = node->next ;
70
+ }
71
+ }
72
+
48
73
int main () {
74
+ ListNode* head = new ListNode (1 );
75
+ head->next = new ListNode (2 );
76
+ head->next ->next = new ListNode (3 );
77
+ head->next ->next ->next = new ListNode (4 );
78
+ head->next ->next ->next ->next = new ListNode (5 );
79
+ head->next ->next ->next ->next ->next = new ListNode (6 );
80
+
81
+ Solution ().reorderList (head);
82
+ printList (head);
83
+
49
84
return 0 ;
50
85
}
0 commit comments