1. 程式人生 > >【LeetCode】【86】【Partition List】【連結串列】

【LeetCode】【86】【Partition List】【連結串列】

題目: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.
解題思路:
借鑑於:https://leetcode.com/problems/partition-list/discuss/29181/10-lines-concise-C++-Solution


雙鏈表法,left連結串列代表的是小於x的值的集合,right連結串列代表的是大於等於x的值的集合。用p和q去連線,注意最後的right = null;
程式碼:

class ListNode {
    int val;
    ListNode next;
    ListNode(int x) {
        val = x;
    }
}
    public ListNode partition(ListNode head, int x) {
        if(head == null) return null;
        ListNode left = new ListNode(-1);
        ListNode right = new ListNode(-1);
        ListNode p = left;
        ListNode q = right;
        while (head!=null){
            if(head.val<x){
                p.next = head;
                p = p.next;
            }else {
                q.next = head;
                q = q.next;
            }
            head = head.next;
        }
        p.next = right.next;
        q.next = null;
        return left.next;
    }