-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathReorder_List.cpp
More file actions
83 lines (83 loc) · 1.65 KB
/
Reorder_List.cpp
File metadata and controls
83 lines (83 loc) · 1.65 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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
int listlength(ListNode* tmp){
int cnt = 0;
while(tmp){
cnt++;
tmp = tmp->next;
}
return cnt;
}
ListNode* reverseBetween(ListNode* A, int B, int C) {
if(!A || !A->next || B==C)
return A;
int count = 1;
ListNode* head = new ListNode(0);
head->next = A;
ListNode* nxt = A->next;
ListNode* prev = head;
while(count<B && A){
count++;
prev = A;
A = A->next;
if(A)
nxt = A->next;
}
ListNode* prev1 = prev;
ListNode* curr1 = A;
prev = NULL;
while(count<=C && A){
count++;
A->next = prev;
prev = A;
A = nxt;
if(A)
nxt = A->next;
}
prev1->next = prev;
curr1->next = A;
return head->next;
}
ListNode* Solution::reorderList(ListNode* A) {
int n = listlength(A);
if(n<3)
return A;
int a,b=n;
if(n&1)
a = (n/2)+2;
else
a = (n/2)+1;
A = reverseBetween(A,a,b);
int cnt=1;
ListNode* prev = NULL;
ListNode* curr = A;
while(cnt<a){
cnt++;
prev = curr;
curr=curr->next;
}
prev->next = NULL;
prev = new ListNode(0);
ListNode* head = prev;
cnt = 0;
while(A || curr){
if(cnt==0){
prev->next = A;
A = A->next;
cnt ^= 1;
}
else{
prev->next = curr;
curr = curr->next;
cnt ^= 1;
}
prev = prev->next;
}
return head->next;
}