思路很简单 按时链表的题做起来很容易犯小错误,思维要缜密
还要多练习啊
做之前最好画算法框图
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; }