-
Notifications
You must be signed in to change notification settings - Fork 0
/
143.cpp
33 lines (33 loc) · 824 Bytes
/
143.cpp
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
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
// 简单但是空间复杂度不是最优的
void reorderList(ListNode* head) {
if (!head or !head->next) return;
ListNode *temp=head;
vector<ListNode *> s;
int count=0,half=1;
while (temp) {
s.push_back(temp);
temp=temp->next;
count++;
}
temp=head;
while (half<=count/2) {
ListNode *next=temp->next;
temp->next=s.back();
s.back()->next=(count%2==0 and half==count/2) ? NULL : next;
s.pop_back();
temp=next;
half++;
}
temp->next=NULL;
}
};