-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathPartition1.java
More file actions
32 lines (27 loc) · 843 Bytes
/
Partition1.java
File metadata and controls
32 lines (27 loc) · 843 Bytes
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
/*
Partition: Write code to partition a linked list around a value x, such that all nodes less than x come
before all nodes greater than or equal to x. If x is contained within the list, the values of x only need
to be after the elements less than x (see below). The partition element x can appear anywhere in the
"right partition"; it does not need to appear between the left and right partitions.
*/
class Partition1 {
public ListNode partition(ListNode head, int x) {
if(head == null || head.next == null){
return head;
}
ListNode left = n,right = n,prev = n,head = n;
while(n != null){
if(n.val >= x){
ListNode temp = n.next;
right = n;
}
else{
//ListNode temp = n.next;
left = n;
right.next = n.next;
left.next = right;
prev = n;
n = n.next;
}
}
}