-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathReorder List.cpp
More file actions
52 lines (51 loc) · 1.3 KB
/
Copy pathReorder List.cpp
File metadata and controls
52 lines (51 loc) · 1.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
//https://leetcode.com/problems/reorder-list/
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution {
public:
ListNode* reverse(ListNode* head){
if(head==NULL || head->next==NULL){
return head;
}
ListNode* n=reverse(head->next);
head->next->next=head;
head->next=NULL;
return n;
}
void reorderList(ListNode* head) {
if(head==NULL || head->next==NULL){
return;
}
ListNode* fast=head;
ListNode* slow=head;
ListNode* prev=NULL;
while(fast && fast->next){
fast=fast->next->next;
prev=slow;
slow=slow->next;
}
prev->next=NULL;
slow=reverse(slow);
fast=head;
ListNode* ans=new ListNode();
ListNode* a=ans;
while(fast && slow){
ans->next=fast; ans=ans->next;
fast=fast->next;
ans->next=slow; ans=ans->next;
slow=slow->next;
}
if(slow && ans)
ans->next=slow;
head=a->next;
return;
}
};