Skip to content

Instantly share code, notes, and snippets.

@daifu
Created February 15, 2013 07:02
Show Gist options
  • Select an option

  • Save daifu/4958913 to your computer and use it in GitHub Desktop.

Select an option

Save daifu/4958913 to your computer and use it in GitHub Desktop.
Given a linked list and a value x, partition it such that all nodes less than x come before nodes greater than or equal to x.
/*
Given a linked list and a value x, partition it such that all nodes less than x come before nodes greater than or equal to x.
You should preserve the original relative order of the nodes in each of the two partitions.
For example,
Given 1->4->3->2->5->2 and x = 3,
return 1->2->2->4->3->5.
*/
public ListNode partition(ListNode head, int x) {
ListNode root = new ListNode(-1);
ListNode pivot = new ListNode(x);
ListNode root_last = root, pivot_last = pivot;
ListNode cur_node = head;
while (cur_node != null) {
ListNode next = cur_node.next;
if (cur_node.val < x) {
root_last.next = cur_node;
root_last = cur_node;
} else {
pivot_last.next = cur_node;
pivot_last = cur_node;
pivot_last.next = null;
}
cur_node = next;
}
root_last.next = pivot.next;
return root.next;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment