File tree Expand file tree Collapse file tree 1 file changed +39
-0
lines changed
Linked_List/143.Reorder-List Expand file tree Collapse file tree 1 file changed +39
-0
lines changed Original file line number Diff line number Diff line change
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
+ };
You can’t perform that action at this time.
0 commit comments