86. Partition List - Medium

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:

Input: head = 1->4->3->2->5->2, x = 3
Output: 1->2->2->4->3->5

 

用两个dummy head,两个dummy tail,分别表示<=x的,和>x的,然后把两个list首尾相连。最后记得把larger list的末尾指向null,防止出现cycle

time: O(n), space: O(1)

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public ListNode partition(ListNode head, int x) {
        if(head == null || head.next == null) {
            return head;
        }
        ListNode dummyHeadSmall = new ListNode(0);
        ListNode dummyHeadLarge = new ListNode(0);
        ListNode dummyTailSmall = dummyHeadSmall;
        ListNode dummyTailLarge = dummyHeadLarge;
        
        ListNode cur = head;
        while(cur != null) {
            if(cur.val < x) {
                dummyTailSmall.next = cur;
                dummyTailSmall = dummyTailSmall.next;
            } else {
                dummyTailLarge.next = cur;
                dummyTailLarge = dummyTailLarge.next;
            }
            cur = cur.next;
        }
        dummyTailSmall.next = dummyHeadLarge.next;
        dummyTailLarge.next = null;
        return dummyHeadSmall.next;
    }
}

 

posted @ 2018-12-26 10:22  fatttcat  阅读(66)  评论(0编辑  收藏  举报