码迷,mamicode.com
首页 > 其他好文 > 详细

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

时间:2018-02-11 21:24:00      阅读:231      评论:0      收藏:0      [点我收藏+]

标签:return   链表   nod   next   public   class   nbsp   分块   span   

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

还要多练习啊

做之前最好画算法框图

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链表分块

标签:return   链表   nod   next   public   class   nbsp   分块   span   

原文地址:https://www.cnblogs.com/stAr-1/p/8443124.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!