forked from Alex-Keyes/InterviewBit
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathpartition.cpp
30 lines (25 loc) · 1020 Bytes
/
partition.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
class Solution {
public:
ListNode *partition(ListNode *head, int x) {
if (!head) return NULL;
ListNode * iterator = head;
ListNode * start = new ListNode(0); // list of nodes greater than x
ListNode * tail = start;
ListNode * newHead = new ListNode(0);
newHead -> next = head;
ListNode * pre = newHead; // previous node, we need it for removing
while (iterator) {
if (iterator -> val >= x) {
pre -> next = iterator -> next; // remove from our list
tail -> next = iterator; // add to list of nodes greater than x
tail = tail -> next;
iterator = iterator -> next;
tail -> next = NULL;
}
else
pre = iterator, iterator = iterator -> next;
}
pre -> next = start -> next;
return newHead -> next;
}
};