Skip to content

Commit 4f77c67

Browse files
committed
Add reorder linked list functions
1 parent e849b90 commit 4f77c67

File tree

2 files changed

+54
-2
lines changed

2 files changed

+54
-2
lines changed

leetcode/linked_list/reorder_list

424 Bytes
Binary file not shown.

leetcode/linked_list/reorder_list.cpp

Lines changed: 54 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -32,7 +32,7 @@ class Solution {
3232
*
3333
* Source: https://www.kancloud.cn/kancloud/data-structure-and-algorithm-notes/73015
3434
*/
35-
void reorderList(ListNode* head) {
35+
void reorderList1(ListNode* head) {
3636
if (head == NULL || head->next == NULL || head->next->next == NULL) {
3737
return;
3838
}
@@ -60,6 +60,58 @@ class Solution {
6060
last = temp;
6161
}
6262
}
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+
}
63115
};
64116

65117
/* Function to print nodes in a given linked list */
@@ -78,7 +130,7 @@ int main() {
78130
head->next->next->next->next = new ListNode(5);
79131
head->next->next->next->next->next = new ListNode(6);
80132

81-
Solution().reorderList(head);
133+
Solution().reorderList2(head);
82134
printList(head);
83135

84136
return 0;

0 commit comments

Comments
 (0)