Skip to content

Commit 2f8e51c

Browse files
authored
Merge pull request #21 from Bill0412/patch-4
Create 143.Reorder-List_v2.cpp
2 parents 47d71ae + fd89446 commit 2f8e51c

File tree

1 file changed

+39
-0
lines changed

1 file changed

+39
-0
lines changed
Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
/**
2+
* Definition for singly-linked list.
3+
* struct ListNode {
4+
* int val;
5+
* ListNode *next;
6+
* ListNode() : val(0), next(nullptr) {}
7+
* ListNode(int x) : val(x), next(nullptr) {}
8+
* ListNode(int x, ListNode *next) : val(x), next(next) {}
9+
* };
10+
*/
11+
class Solution {
12+
public:
13+
void reorderList(ListNode* head) {
14+
ListNode *slow = head, *fast = head;
15+
for(; fast && fast->next; slow = slow->next, fast = fast->next->next);
16+
ListNode *head1 = head;
17+
ListNode *head2 = slow->next;
18+
slow->next = nullptr;
19+
20+
// reverse list2
21+
ListNode *nextNode = nullptr;
22+
for(ListNode *cur = head2; cur != nullptr;) {
23+
ListNode *curNext = cur->next;
24+
cur->next = nextNode;
25+
nextNode = cur;
26+
cur = curNext;
27+
}
28+
head2 = nextNode;
29+
30+
// traverse list1 to insert
31+
for(ListNode *ptr1 = head1, *ptr2 = head2; ptr1 && ptr2;) {
32+
ListNode *ptr1Next = ptr1->next, *ptr2Next = ptr2->next;
33+
ptr1->next = ptr2;
34+
ptr2->next = ptr1Next;
35+
ptr1 = ptr1Next;
36+
ptr2 = ptr2Next;
37+
}
38+
}
39+
};

0 commit comments

Comments
 (0)