[LintCode]Partition List
/**
* 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) {
// 2015-4-24
if (head == null) {
return head;
}
// 两个新的链表
ListNode dummyA = new ListNode(0);
ListNode nodeA = dummyA;
ListNode dummyB = new ListNode(0);
ListNode nodeB = dummyB;
while (head != null) {
if (head.val < x) {
nodeA.next = head;
nodeA = nodeA.next;
} else {
nodeB.next = head;
nodeB = nodeB.next;
}
head = head.next;
}
nodeA.next = dummyB.next;
nodeB.next = null;
return dummyA.next;
}
}