Skip to content

Commit e849b90

Browse files
committed
Add reorder linked list function
1 parent 6bc78b9 commit e849b90

File tree

2 files changed

+36
-1
lines changed

2 files changed

+36
-1
lines changed

leetcode/linked_list/reorder_list

8.85 KB
Binary file not shown.

leetcode/linked_list/reorder_list.cpp

Lines changed: 36 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,8 @@ class Solution {
2929
*
3030
* Example:
3131
* 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
3234
*/
3335
void reorderList(ListNode* head) {
3436
if (head == NULL || head->next == NULL || head->next->next == NULL) {
@@ -41,10 +43,43 @@ class Solution {
4143
last = last->next;
4244
++length;
4345
}
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+
}
4562
}
4663
};
4764

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+
4873
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+
4984
return 0;
5085
}

0 commit comments

Comments
 (0)