Problem
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.
Example
Given 1->4->3->2->5->2->null
and x = 3
,
return 1->2->2->4->3->5->null
.
Note
新建两个链表,分别存<x
和>=x
的结点。令头结点分别叫作dummyleft
和dummyright
,对应的指针分别叫作left
和right
。然后遍历head
,当head.val
小于x
的时候放入left.next,否则放入right.next
。最后,让较小值链表尾结点left
指向较大值链表头结点dummyright.next
,再让较大值链表尾结点right
指向null
。这样两个新链表就相连了,返回头结点dummyleft.next
即可。
Solution
public class Solution {
public ListNode partition(ListNode head, int x) {
ListNode dummyleft = new ListNode(0);
ListNode dummyright = new ListNode(0);
ListNode left = dummyleft, right = dummyright;
while (head != null) {
if (head.val < x) {
left.next = head;
left = left.next;
}
else {
right.next = head;
right = right.next;
}
head = head.next;
}
left.next = dummyright.next;
right.next = null;
return dummyleft.next;
}
}