-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathPartition_List.cpp
38 lines (35 loc) · 918 Bytes
/
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
// http://oj.leetcode.com/problems/partition-list/
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode *partition(ListNode *head, int x) {
if (head == nullptr) return head;
ListNode left_dummy(0);
ListNode right_dummy(0);
auto left_cur = &left_dummy;
auto right_cur = &right_dummy;
for (; head; head = head->next)
{
if (head->val < x)
{
left_cur->next = head;
left_cur = head;
}
else
{
right_cur->next = head;
right_cur = head;
}
}
left_cur->next = right_dummy.next;
right_cur->next = nullptr;
return left_dummy.next;
}
};