[Data Structure and Algorithm] Linked List-Separated Linked List

Separated linked list

LeetCode: Separated linked list

Title description:

Given a linked list whose head node is root, write a function to divide the linked list into k consecutive parts.

The length of each part should be as equal as possible: the difference between the lengths of any two parts cannot exceed 1, which means that some parts may be null.

The k parts should be output in the order in which they appear in the linked list, and the length of the front part should be greater than or equal to the back length.

Return a list of linked lists that meet the above rules.

Example: 1-> 2-> 3-> 4, k = 5 // 5 results [[1], [2], [3], [4], null]

Examples:

输入: 
root = [1, 2, 3], k = 5
输出: [[1],[2],[3],[],[]]
解释:
输入输出各部分都应该是链表,而不是数组。
例如, 输入的结点 root 的 val= 1, root.next.val = 2, \root.next.next.val = 3, 且 root.next.next.next = null。
第一个输出 output[0] 是 output[0].val = 1, output[0].next = null。
最后一个元素 output[4] 为 null, 它代表了最后一个部分为空链表。

thought:

No idea, it is to traverse once to get the length of the linked list, and then find the separation point to divide. The main reason is that the code logic is a bit complicated and requires more practice.

Code:

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public ListNode[] splitListToParts(ListNode root, int k) {
        int len=0;
        ListNode p=root,pre=null;
        while(p!=null){
            ++len;
            p=p.next;
        }
        int base=len/k,add=len%k,i=0,count=0;
        p=root;
        ListNode[] res = new ListNode[k];
        while(p!=null){
            if(count ==0){
                if(pre!=null)
                    pre.next = null;
                res[i++]=p;
                count = base + (add-->0?1:0);
            }
            --count;
            pre=p;
            p=p.next;
        }
        return res;
    }
}

Guess you like

Origin www.cnblogs.com/buptleida/p/12689611.html