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;
    }
}

猜你喜欢

转载自blog.csdn.net/Sunshine_liang1/article/details/84561151
今日推荐