-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path143.ReorderList.cpp
More file actions
53 lines (53 loc) · 1.23 KB
/
143.ReorderList.cpp
File metadata and controls
53 lines (53 loc) · 1.23 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
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
int length(ListNode* head){
int count = 0;
while(head!= NULL){
count++;
head = head->next;
}
return count;
}
void reorderList(ListNode* head) {
stack<ListNode*> s;
queue<ListNode*> q;
if(head == NULL || head->next==NULL)
return;
ListNode* node = head;
int len = length(head);
int count = 0;
while(count++ < len/2){
q.push(node);
node = node->next;
}
count--;
while(count++ < len){
s.push(node);
node = node->next;
}
q.pop();
node = head;
while(!(s.empty()&&q.empty())){
cout << node->val << endl;
if(!s.empty()){
node->next = s.top();
s.pop();
node = node->next;
}
if(!q.empty()){
node->next = q.front();
q.pop();
node = node->next;
}
}
node->next = NULL;
}
};