Skip to content

Instantly share code, notes, and snippets.

@alexandervasyuk
Created September 26, 2014 18:10
Show Gist options
  • Save alexandervasyuk/fb24a5aa16bfee1a9755 to your computer and use it in GitHub Desktop.
Save alexandervasyuk/fb24a5aa16bfee1a9755 to your computer and use it in GitHub Desktop.
Partition linked list around x
public Node partition(Node node, int x) {
Node lessHead, lessTail, greaterHead, greaterTail;
while (node != null) {
Node next = node.next;
node.next = null;
if (node.data < x) {
if (lessHead == null) {
lessHead = lessTail = node;
} else {
lessTail.next = node;
lessTail = lessTail.next;
}
} else {
if (greaterHead == null) {
greaterHead = greaterTail = node;
} else {
greaterTail.next = node;
greaterTail = greaterTail.next;
}
}
node = next;
}
if (lessHead == null) return graterHead;
lesstTail.next = greaterHead;
return lessHead;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment