[LintCode/LeetCode] Partition List

386 查看

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的结点。令头结点分别叫作dummyleftdummyright,对应的指针分别叫作leftright。然后遍历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;
    }
}