-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathPartition_List.cpp
74 lines (41 loc) · 1.15 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
45
46
/**
* 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 == NULL || (head != NULL && head->next == NULL))
return head;
ListNode *insert_pointer = NULL, *cur = head;
while(cur->next != NULL) {
/* find the insert pointer: cur */
if(insert_pointer == NULL && cur->val < x && cur->next->val >= x) {
insert_pointer = cur;
cur = cur->next;
continue;
}
/* cur->next is the node that should be moved forward */
if(cur->val >= x && cur->next->val < x) {
ListNode *t = cur->next;
cur->next = t->next;
if(insert_pointer == NULL) {
t->next = head;
head = t;
} else {
t->next = insert_pointer->next;
insert_pointer->next = t;
}
insert_pointer = t;
continue;
}
/* other cases */
cur = cur->next;
}
return head;
}
};