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

你可能感兴趣的:(Split Linked List in Parts)