Created
June 26, 2014 22:41
-
-
Save JoyceeLee/f0c185fa59129c3f74d4 to your computer and use it in GitHub Desktop.
This file contains 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
/*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