Skip to content

Instantly share code, notes, and snippets.

@charlespunk
Created October 20, 2013 02:27
Show Gist options
  • Save charlespunk/7064167 to your computer and use it in GitHub Desktop.
Save charlespunk/7064167 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.
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.
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
public ListNode partition(ListNode head, int x) {
// Note: The Solution object is instantiated only once and is reused by each test case.
LinkedList<ListNode> front = new LinkedList<ListNode>();
LinkedList<ListNode> back = new LinkedList<ListNode>();
while(head != null){
ListNode run = head;
if(run.val < x) front.push(run);
else back.push(run);
head = head.next;
}
ListNode end = null;
while(!back.isEmpty()){
ListNode run = back.pop();
run.next = end;
end = run;
}
while(!front.isEmpty()){
ListNode run = front.pop();
run.next = end;
end = run;
}
return end;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment