Created
October 20, 2013 02:27
-
-
Save charlespunk/7064167 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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. |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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