Skip to content

Instantly share code, notes, and snippets.

@charlespunk
Last active December 12, 2015 12:19
Show Gist options
  • Save charlespunk/4770806 to your computer and use it in GitHub Desktop.
Save charlespunk/4770806 to your computer and use it in GitHub Desktop.
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.
public static void partitionList(Node root, int x){
Node bigger = null;
Node smaller = null;
while(root != null){
if(root.value >= x){
if(bigger == null) bigger = root;
else{
bigger.next = root;
bigger = root;
}
}
else{
if(smaller == null) smaller = root;
else{
root.next = smaller;
smaller = root;
}
}
}
if(bigger == null || smaller == null) return (bigger != null)? bigger : smaller;
else{
bigger.next = smaller;
return bigger;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment