首页 > 代码库 > 86. Partition List

86. Partition List

https://leetcode.com/problems/partition-list/#/description

http://www.cnblogs.com/EdwardLiu/p/3807137.html

Analysis: Linked List 惯用套路,Runner Technique(Two Pointers), 一些技巧就是:设置head的前置假节点prev,两个pointer:current和runner都指到这个prev,然后进行判断总是判断 current.next 或者 runner.next. 这样做按照我多次做类似题的经验来说,是最方便省事不容易出错的。思路就是current 和 runner 一直移动直到找到 current.next >= x 为止,这里就是后面小于x的元素将要插入的位置,current便停在这里,指示这个位置,runner继续往后面寻找,把每一个小于x的元素都插入到current.next 的位置。

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
public class Solution {
    public ListNode partition(ListNode head, int x) {
        if (head == null) {
            return head;
        }
        ListNode dummy = new ListNode(-1);
        dummy.next = head;
        ListNode tail = dummy;
        ListNode pre = dummy;
        while (dummy.next != null && dummy.next.val < x) {
            dummy = dummy.next;
            tail = tail.next;
        }
        while (tail.next != null) {
            if (tail.next.val < x) {
                ListNode temp = tail.next;
                tail.next = tail.next.next;
                temp.next = dummy.next;
                dummy.next = temp;
                dummy = dummy.next;    
            } else {
                tail = tail.next;
            }
        }    
        return pre.next;   
    }
}

  

86. Partition List