-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path143.重排链表.cpp
49 lines (43 loc) · 914 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
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
/*
* @lc app=leetcode.cn id=143 lang=cpp
*
* [143] 重排链表
*/
// @lc code=start
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
#include <vector>
class Solution {
public:
void reorderList(ListNode* head) {
if(head == nullptr) return;
std::vector<ListNode*> v;
auto* h = head;
while(h != nullptr){
v.emplace_back(h);
h = h->next;
}
auto it = v.begin();
auto jt = v.end() - 1;
bool flag = true;
while(it != jt){
if(flag){
(*it)->next = *jt;
++it;
}
else{
(*jt)->next = *it;
--jt;
}
flag ^= true;
}
(*it)->next = nullptr;
}
};
// @lc code=end