-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPartitionList.cc
More file actions
42 lines (38 loc) · 1.08 KB
/
PartitionList.cc
File metadata and controls
42 lines (38 loc) · 1.08 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
namespace PartitionList {
class Solution {
public:
ListNode *partition(ListNode *head, int x) {
if (head == NULL) {
return NULL;
}
ListNode dummy(-1);
dummy.next = head;
ListNode * prev = &dummy;
ListNode * cur = head;
// find the first num >= x
while (cur != NULL && cur->val < x) {
cur = cur->next;
prev = prev->next;
}
ListNode * dest = prev;
if (cur != NULL) {
cur = cur->next;
prev = prev->next; // move forward 1 step
}
// keep going, once find a num < x, mov it
while (cur != NULL) {
if (cur->val < x) {
prev->next = cur->next;
cur->next = dest->next;
dest->next = cur;
cur = prev->next;
dest = dest->next;
} else {
cur = cur->next;
prev = prev->next;
}
}
return dummy.next;
}
};
}