-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpartition.cpp
47 lines (42 loc) · 1.27 KB
/
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
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
/********************************************************************
Copyright : CNIC
Author : LiuYao
Date : 2017-9-1
Description : leetcode 86. Partition List
********************************************************************/
#include <cstddef>
// Definition for singly-linked list.
struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
ListNode* partition(ListNode* head, int x) {
ListNode* newHead = new ListNode(0);
newHead -> next = head;
ListNode* l_end, *r_start, *cur = newHead;
//find the first element greater than x,
//store the l_end and r_start
while(cur -> next && cur -> next -> val < x){
cur = cur -> next;
}
if(!cur -> next) return newHead -> next;
l_end = cur;
r_start = cur -> next;
//traverse the rest linked list,
//if the element grater than x, insert it to the position
//between l_end and r_start, else continue.
ListNode* slow = r_start, *fast = slow -> next;
while(fast){
if(fast -> val < x){
slow -> next = fast -> next;
l_end -> next = fast;
fast -> next = r_start;
l_end = fast;
}else{
slow = fast;
}
fast = slow -> next;
}
return newHead -> next;
}