-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathreorder_list.cpp
More file actions
62 lines (59 loc) · 1.45 KB
/
reorder_list.cpp
File metadata and controls
62 lines (59 loc) · 1.45 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
62
/*
* =====================================================================================
*
* Filename: reorder_list.cpp
*
* Description: 143. Reorder List. https://leetcode.com/problems/reorder-list
*
* Version: 1.0
* Created: 10/24/2021 20:59:44
* Revision: none
* Compiler: gcc
*
* Author: xianfeng.zhu@gmail.com
* Organization:
*
* =====================================================================================
*/
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) {}
};
// Recursion
class Solution {
public:
void reorderList(ListNode* head) {
ListNode* ptr = head;
ListNode* tail = head;
bool reordered = false;
reorderList(head, tail, ptr, reordered);
}
void reorderList(ListNode*& head, ListNode* tail, ListNode*& ptr, bool& reordered) {
if (tail == nullptr) {
return;
}
reorderList(head, tail->next, ptr, reordered);
if (reordered) {
return;
}
if (head == tail || head->next == tail) {
if (tail->next != nullptr) {
tail->next = nullptr;
}
reordered = true;
return;
}
head = head->next;
tail->next = head;
ptr->next = tail;
ptr = head;
}
};
int main(int argc, char* argv[]) {
ListNode* head = nullptr;
Solution().reorderList(head);
return 0;
}