86. Partition List

weixin_34253539發表於2019-02-12

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

難度:medium

題目:給定連結串列和一指定值X,以X為參照將連結串列劃分為小於X和大於等於X兩部分。保持原始連結串列中結點的順序不變。

思路:將原始連結串列先拆分為兩連結串列,一個收集所以小於X的,一個收集其它的。然後合併兩連結串列。

Runtime: 0 ms, faster than 100.00% of Java online submissions for Partition List.
Memory Usage: 36.7 MB, less than 0.90% of Java online submissions for Partition List.

/**
 * 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) {
        ListNode lHead = new ListNode(0), lTail = lHead;
        ListNode geHead = new ListNode(0), geTail = geHead;
        ListNode ptr = head, node = null;
        while (ptr != null) {
            node = ptr;
            ptr = ptr.next;
            if (node.val < x) {
                lTail.next = node;
                lTail = node;
            } else {
                geTail.next = node;
                geTail = node;
            }
        }
        
        lTail.next = geHead.next;
        geTail.next = null;
        
        return lHead.next;
    }
}

相關文章