[leetcode]725. Split Linked List in Parts链表分块

Posted stAr_1

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[leetcode]725. Split Linked List in Parts链表分块相关的知识,希望对你有一定的参考价值。

思路很简单  按时链表的题做起来很容易犯小错误,思维要缜密

还要多练习啊

做之前最好画算法框图

public ListNode[] splitListToParts(ListNode root, int k) {
        ListNode[] res = new ListNode[k];
        int count = 0;
        ListNode temp = root;
        //计算长度
        while (temp!=null)
        {
            count++;
            temp = temp.next;
        }
        //计算链表长度
        int size = count/k;
        int a = size;
        int y = count%k;
        ListNode sta = root;
        //前几个多的
        for (int i = 0; i < y; i++) {
            ListNode cur = root;
            while (size>0&&root!=null)
            {
                root = root.next;
                size--;
            }
            size = a;
            sta = root.next;
            root.next = null;
            root = sta;
            res[i] = cur;
        }
        //后几个少的
        for (int i = y; i < k; i++) {
            ListNode cur = root;
            while (size>1&&root!=null)
            {
                root = root.next;
                size--;
            }
            size = a;
            if (root!=null) {
                sta = root.next;
                root.next = null;
            }
            else sta = null;
            root = sta;
            res[i] = cur;
        }
        return res;
    }

 

以上是关于[leetcode]725. Split Linked List in Parts链表分块的主要内容,如果未能解决你的问题,请参考以下文章

LeetCode 725. Split Linked List in Parts (分裂链表)

[leetcode]725. Split Linked List in Parts链表分块

LC 725. Split Linked List in Parts

725. Split Linked List in Parts 拆分链表

725. Split Linked List in Parts把链表分成长度不超过1的若干部分

leetcode725