-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLeetCode-PartitionList.cpp
More file actions
37 lines (29 loc) · 1.02 KB
/
LeetCode-PartitionList.cpp
File metadata and controls
37 lines (29 loc) · 1.02 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
class Solution {
public:
ListNode* partition(ListNode* head, int x) {
if (head == nullptr)
return nullptr;
vector<ListNode*> left;
vector<ListNode*> right;
ListNode * cur = head;
while (cur != nullptr) {
if (cur->val < x)
left.push_back(cur);
else
right.push_back(cur);
cur = cur->next;
}
for (int i = 0; i < left.size() + right.size() - 1; ++i)
if (i < (int)left.size() - 1)
(left[i])->next = left[i+1];
else if (i == (int)left.size() - 1)
(left[i])->next = right[0];
else
(right[i-left.size()])->next = right[i+1-left.size()];
if (right.size() > 0)
(right[right.size() - 1])->next = nullptr;
else
(left[left.size() - 1])->next = nullptr;
return left.size() > 0 ? left[0] : right[0];
}
};