【Leetcode】86. Partition List

於淼發表於2018-02-26

Question:

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.

For example,
Given 1->4->3->2->5->2 and x = 3,
return 1->2->2->4->3->5.

Tips:

給定一個無序的連結串列,將連結串列分成兩部分,前半部分的val全部小於x;後半部分大於等於x。

前後兩部分的結點,相對位置不變,即node1 與node2 均大於x 那麼不管node1與node2的val誰大,最終順序仍未node1->node2.

思路:

初始化兩個頭結點small 與big,然後開始遍歷連結串列,當head.val>=x ,就將head接到big.next上。否則接到small.next上。

head走到末尾,將small的最後一個結點與big的第一個結點連線,返回small的第一個結點即可。

程式碼:

 

public ListNode partition(ListNode head, int x) {
        if (head == null)
            return head;
        ListNode big = new ListNode(-1);
        ListNode small = new ListNode(-1);
        ListNode temp = big;// 記錄big的第一個結點位置
        ListNode result = small;// 記錄small的第一個結點位置
        while (head != null) {
            if (head.val >= x) {
                big.next = head;
                big = big.next;

            } else {
                small.next = head;
                small = small.next;
            }
            head = head.next;
        }
        //small的最後一個結點與big的第一個結點連線
        small.next = temp.next;
        big.next = null;
        return result.next;
    }

 

測試程式碼:

public static void main(String[] args) {
        L86PartitionList l86 = new L86PartitionList();
        ListNode head1 = new ListNode(1);
        ListNode head2 = new ListNode(4);
        ListNode head3 = new ListNode(2);
        ListNode head4 = new ListNode(5);
        ListNode head5 = new ListNode(3);
        ListNode head6 = new ListNode(6);
        ListNode head7 = null;
        head1.next = head2;
        head2.next = head3;
        head3.next = head4;
        head4.next = head5;
        head5.next = head6;
        head6.next = head7;
        ListNode head = l86.partition(head1, 30);
        while (head != null) {
            System.out.println(head.val);
            head = head.next;
        }
    }

 

相關文章