1. 程式人生 > >leetcode:725. Split Linked List in Parts(Medium)(java)

leetcode:725. Split Linked List in Parts(Medium)(java)

題目:

Given a (singly) linked list with head node root, write a function to split the linked list into k consecutive linked list "parts".

The length of each part should be as equal as possible: no two parts should have a size differing by more than 1. This may lead to some parts being null.

The parts should be in order of occurrence in the input list, and parts occurring earlier should always have a size greater than or equal parts occurring later.

Return a List of ListNode's representing the linked list parts that are formed.

Examples 1->2->3->4, k = 5 // 5 equal parts [ [1], [2], [3], [4], null ]

Example 1:

Input: 
root = [1, 2, 3], k = 5
Output: [[1],[2],[3],[],[]]

題目描述:

     將連結串列分隔成k部分,每部分的長度最大相差1,排在前面的長度要不小於後面的長度。

解題思路: 

       首先,遍歷連結串列記錄處連結串列的長度N,然後用N/k表示將連結串列平均分成k部分時每部分的長度,N%K表示平均分後剩下的部分,由於要求每部分的長度最多相差1,且排在前面的長度應該大於等於後面的長度,則將前N%k部分分別將長度N/k加1(curSize=size+(mod-->0?1:0)),注意,在連結串列指標指向連結串列每部分的最後一個節點時退出迴圈,將連結串列斷開,然後進行下一次大迴圈。具體思路及程式碼如下:

package Leetcode_Github;

public class DataStructure_LinkedList_SplitListToParts_725_1127 {
    public ListNode[] splitListToParts(ListNode root, int k) {
        int count = 0;
        ListNode curNode = root;
        while (curNode != null) {
            count++;
            curNode = curNode.next;
        }

        int size = count / k;
        int mod = count % k;

        ListNode[] result = new ListNode[k];
        curNode = root;
        for (int i = 0; curNode != null && i < k; i++) {
            result[i] = curNode;
            int curSize = size + (mod-- > 0 ? 1 : 0);
            for (int j = 0; curNode != null && j < curSize - 1; j++) {
                curNode = curNode.next;
            }
            ListNode nextNode = curNode.next;
            curNode.next = null;
            curNode = nextNode;
        }
        return result;
    }
}