forked from kamyu104/LintCode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
partition-list.cpp
47 lines (41 loc) · 1.02 KB
/
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
// Time: O(n)
// Space: O(1)
/**
* Definition of ListNode
* class ListNode {
* public:
* int val;
* ListNode *next;
* ListNode(int val) {
* this->val = val;
* this->next = NULL;
* }
* }
*/
class Solution {
public:
/**
* @param head: The first node of linked list.
* @param x: an integer
* @return: a ListNode
*/
ListNode *partition(ListNode *head, int x) {
ListNode *dummy_smaller = new ListNode(INT_MIN);
ListNode *dummy_larger = new ListNode(INT_MIN);
ListNode *smaller = dummy_smaller;
ListNode *larger = dummy_larger;
while (head) {
if (head->val < x) {
smaller->next = head;
smaller = smaller->next;
} else {
larger->next = head;
larger = larger->next;
}
head = head->next;
}
smaller->next = dummy_larger->next;
larger->next = nullptr;
return dummy_smaller->next;
}
};