题目描述
Given a singly linked list L: L0→L1→…→Ln-1→Ln,
reorder it to: L0→Ln→L1→Ln-1→L2→Ln-2→…
You must do this in-place without altering the nodes' values.
For example,
Given{1,2,3,4}, reorder it to{1,4,2,3}.
--------------------------------------------------------------------------------------------------------------------------------
代码
语言:C++
运行时间: <1 ms
占用内存:9740K
状态:答案正确
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
|
/**
* 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 || !head->next)
return
;
vector<
int
> v;
ListNode* p = head;
while
(p){
v.push_back(p->val);
p = p->next;
}
p = head;
int
i =
0
,j = v.size()-
1
,index =
0
;
while
(i<=j){
if
(index%
2
==
0
){
p->val = v[i++];
}
else
{
p->val = v[j--];
}
p = p->next;
++index;
}
}
};
|