Skip to content

Instantly share code, notes, and snippets.

@JoyceeLee
Created June 26, 2014 22:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save JoyceeLee/f0c185fa59129c3f74d4 to your computer and use it in GitHub Desktop.
Save JoyceeLee/f0c185fa59129c3f74d4 to your computer and use it in GitHub Desktop.
/*2.4 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 class Solution {
public ListNode partition(ListNode head, x) {
ListNode pre = null;
ListNode post = null;
while(head!=null) {
ListNode tmp = head.next;
if(head.val<x) {
head.next = pre;
pre = head;
} else {
head.next = post;
post = head;
}
head = tmp;
}
if(pre==null) {
return post;
}
ListNode run = pre;
while(run.next!=null) {
run = run.next;
}
run.next = post;
return pre;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment