-
Notifications
You must be signed in to change notification settings - Fork 53
Expand file tree
/
Copy path86. Partition List
More file actions
51 lines (50 loc) · 1.39 KB
/
86. Partition List
File metadata and controls
51 lines (50 loc) · 1.39 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.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode partition(ListNode head, int x) {
int target = x;
ListNode firstTarget = null, currentTarget = null
, firstLower = null, currentLower = null, mover;
if(head == null){
return null;
}
mover = head;
while(mover != null){
if(mover.val < target){
if(firstLower == null){
firstLower = mover;
currentLower = mover;
}
else{
currentLower = currentLower.next = mover;
}
}
else{
if(firstTarget == null){
firstTarget = mover;
currentTarget = mover;
}
else{
currentTarget = currentTarget.next = mover;
}
}
mover = mover.next;
}
if(firstLower != null){
if(firstTarget != null){
currentLower.next = firstTarget;
currentTarget.next = null;
}
return firstLower;
}
else{ //firstLower == null -- just attach middle
return firstTarget;
}
}
}