-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path143.Reorder List
55 lines (53 loc) · 1.15 KB
/
143.Reorder List
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
53
54
55
/**
* 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) {}
* };
*/
ListNode* mid(ListNode* head)
{
ListNode* slow=head;
ListNode* fast=head;
while(fast!=nullptr &&fast->next!=nullptr)
{ slow=slow->next;
fast=fast->next->next;
}
return slow;
}
ListNode* reverse(ListNode* node)
{ if(node->next==NULL||node==NULL)
{
return node;
}
ListNode* pi=reverse(node->next);
node->next->next=node;
node->next=nullptr;
return pi;
}
class Solution {
public:
void reorderList(ListNode* head) {
if(head==NULL||head->next==NULL){
return;}
ListNode* temp=head;
ListNode* pi=mid(head);
ListNode* ps=reverse(pi);
ListNode* pt=ps;
while(pt!=nullptr && temp!=nullptr)
{ ListNode* temp2=temp->next;
temp->next=pt;
temp=temp2;
temp2=pt->next;
pt->next=temp;
pt=temp2;
}
if(temp!=NULL)
{ temp->next=NULL;
}
return;
}
};