-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathReorder List.cpp
More file actions
61 lines (61 loc) · 1.4 KB
/
Copy pathReorder List.cpp
File metadata and controls
61 lines (61 loc) · 1.4 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
/**
* 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:
void reorderList(ListNode* head)
{
if(head==NULL || head->next==NULL || head->next->next==NULL)
{
return;
}
ListNode *p,*t;
p=head;
int cnt=0,i;
ListNode *temp=new ListNode(p->val);
temp->next=NULL;
p=p->next;
cnt++;
while(p!=NULL)
{
ListNode *temp1=new ListNode(p->val);
temp1->next=temp;
temp=temp1;
p=p->next;
cnt++;
}
p=head;
//cnt=cnt-1;
t=head->next;
i=2;
while(i<=cnt)
{
if(i%2==0)
{
ListNode *q=new ListNode(temp->val);
temp=temp->next;
p->next=q;
q->next=NULL;
p=p->next;
}
if(i%2!=0)
{
ListNode *q=new ListNode(t->val);
t=t->next;
p->next=q;
q->next=NULL;
// t=t->next;
p=p->next;
}
i++;
}
p->next=NULL;
}
};