-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy path0086-partition-list.cpp
More file actions
51 lines (47 loc) · 1.24 KB
/
0086-partition-list.cpp
File metadata and controls
51 lines (47 loc) · 1.24 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
43
44
45
46
47
48
49
50
51
/**
* 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) {
return NULL;
}
ListNode* p1 = head, *p2 = head;
ListNode* right_head = NULL, *right_p1 = NULL;
for (; p2 != NULL; ) {
if (p2->val < x) {
p1 = p2;
p2 = p2->next;
} else {
if (right_p1 == NULL) {
right_head = right_p1 = p2;
} else {
right_p1->next = p2;
right_p1 = p2;
}
p2 = p2->next;
if (p1->next == p2) {
if (p1 == head) {
head = p2;
}
p1 = p2;
} else {
p1->next = p2;
}
right_p1->next = NULL;
}
}
if (p1 != NULL) {
p1->next = right_head;
return head;
} else {
return right_head;
}
}
};