Split Linked List in Parts

题目
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 ]

答案

class Solution {
    public ListNode[] splitListToParts(ListNode root, int k) {
        if(root == null) return new ListNode[k];
        List<ListNode> arrlist = new ArrayList<>();
        for(ListNode i = root; i != null; i = i.next) {
            arrlist.add(i);
        }
        int len = arrlist.size();
        int part_len = len / k, extras = len % k;

        ListNode[] list = new ListNode[k];
        int j = 0;
        for(int i = 0; i < k; i++) {
            int actual_part_len = part_len;
            if(i < extras) actual_part_len += 1;
            if(actual_part_len == 0) {
                list[i] = null;
                continue;
            }
            // Add part to list to be returned
            list[i] = arrlist.get(j);
            ListNode curr = list[i];

            // Cut current part from next part
            for(int p = 0; p < actual_part_len - 1; p++)
                curr = curr.next;
            curr.next = null;

            j += actual_part_len;
        }
        return list;
    }
}
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

友情链接更多精彩内容