This is my code to partition a list into two parts according to a value. I.e. nodes smaller than value x
should precede nodes larger than the value x
.
It seems correct. Any corner cases I am overseeing or corrections are highly appreciated.
public Node partition(Node head, int x){
if(head == null) return head;
Node prev = null;
Node current = head;
while(current != null){
if(current.data > x || current == head){
prev = current;
current = current.next;
}
else{
Node next = current.next;
current.next = head;
if(prev != null) {
prev.next = next;
}
head = current;
current = next;
}
}
return head;
}