-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy path0086-partition-list.cpp
54 lines (51 loc) · 1.47 KB
/
0086-partition-list.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
49
50
51
52
53
54
/**
* Definition for singly-linked list.
* 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) {}
* };
*/
// class Solution {
// public:
// ListNode* partition(ListNode* head, int x) {
// auto res = new ListNode();
// auto itr = head, cache = res;
// while (itr) {
// if (itr->val < x)
// res->next = new ListNode(itr->val),
// res = res->next;
// itr = itr->next;
// }
// itr = head;
// while (itr) {
// if (itr->val >= x)
// res->next = new ListNode(itr->val),
// res = res->next;
// itr = itr->next;
// }
// return cache->next;
// }
// };
class Solution {
public:
ListNode* partition(ListNode* head, int x) {
auto less = new ListNode(-1, NULL), itr_less = less;
auto more = new ListNode(-1, NULL), itr_more = more;
auto curr = head;
while (curr) {
if (curr->val < x)
itr_less->next = curr,
itr_less = itr_less->next;
else
itr_more->next = curr,
itr_more = itr_more->next;
curr = curr->next;
}
itr_more->next = NULL;
itr_less->next = more->next;
return less->next;
}
};