Skip to content

Commit 873bf46

Browse files
Linked List [Reorder]
1 parent 0ce3cf5 commit 873bf46

File tree

1 file changed

+61
-0
lines changed

1 file changed

+61
-0
lines changed

Solutions/143.cpp

Lines changed: 61 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,61 @@
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+
ListNode* rev(ListNode* head){
14+
if(head == NULL){
15+
return NULL;
16+
}
17+
18+
ListNode* prev = NULL;
19+
ListNode* curr = head;
20+
ListNode* next;
21+
while(curr){
22+
next = curr -> next;
23+
curr -> next = prev;
24+
prev = curr;
25+
curr = next;
26+
}
27+
28+
return prev;
29+
}
30+
void reorderList(ListNode* head) {
31+
if(head==NULL||head->next==NULL||head->next->next==NULL){
32+
return;
33+
}
34+
/// Find middle Node
35+
ListNode* slow = head;
36+
ListNode* fast = head -> next;
37+
38+
while(fast && fast -> next){
39+
slow = slow -> next;
40+
fast = fast -> next -> next;
41+
}
42+
43+
ListNode* secHead = slow -> next;
44+
slow -> next = NULL;
45+
46+
/// Reverse 2nd list
47+
secHead = rev(secHead);
48+
ListNode* tmp1 = head;
49+
ListNode* tmp2 = secHead;
50+
51+
while(tmp1 && tmp2){
52+
ListNode* curr1 = tmp1 -> next;
53+
ListNode* curr2 = tmp2 -> next;
54+
55+
tmp1 -> next = tmp2;
56+
tmp2 -> next = curr1;
57+
tmp1 = curr1;
58+
tmp2 = curr2;
59+
}
60+
}
61+
};

0 commit comments

Comments
 (0)
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy