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;
}
}
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用。你还可以使用@来通知其他用户。