Skip to content

Instantly share code, notes, and snippets.

@cxtadment
Created September 1, 2015 17:03
Show Gist options
  • Select an option

  • Save cxtadment/2bdc73e3c9cf086a5b64 to your computer and use it in GitHub Desktop.

Select an option

Save cxtadment/2bdc73e3c9cf086a5b64 to your computer and use it in GitHub Desktop.
/**
* Definition for ListNode.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int val) {
* this.val = val;
* this.next = null;
* }
* }
*/
public class Solution {
/**
* @param head: The first node of linked list.
* @param x: an integer
* @return: a ListNode
*/
public ListNode partition(ListNode head, int x) {
// write your code here
// idea: use two pointer to record smaller partion and larger partion elements separately
if (head == null) {
return null;
}
ListNode leftDummy = new ListNode(0);
ListNode left = leftDummy;
ListNode rightDummy = new ListNode(1);
ListNode right = rightDummy;
while (head != null) {
if (head.val < x) {
left.next = head;
left = left.next;
} else {
right.next = head;
right = right.next;
}
head = head.next;
}
right.next = null;
left.next = rightDummy.next;
return leftDummy.next;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment