21. 分隔链表
题目描述
给定一个头结点为 root
的链表, 编写一个函数以将链表分隔为 k
个连续的部分。
每部分的长度应该尽可能的相等: 任意两部分的长度差距不能超过 1,也就是说可能有些部分为 null。
这k个部分应该按照在链表中出现的顺序进行输出,并且排在前面的部分的长度应该大于或等于后面的长度。
返回一个符合上述规则的链表的列表。
举例: 1->2->3->4, k = 5 // 5 结果 [ [1], [2], [3], [4], null ]
示例1:
输入:
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, 它代表了最后一个部分为空链表。
示例2
输入:
root = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10], k = 3
输出: [[1, 2, 3, 4], [5, 6, 7], [8, 9, 10]]
解释:
输入被分成了几个连续的部分,并且每部分的长度相差不超过1.前面部分的长度大于等于后面部分的长度。
提示:
root
的长度范围:[0, 1000]
.- 输入的每个节点的大小范围:
[0, 999]
. k
的取值范围:[1, 50]
.
代码:
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
static class ListNode {
int val;
ListNode next;
ListNode(int x) {
val = x;
next = null;
}
@Override
public String toString() {
return "ListNode{" +
"val=" + val +
", next=" + next +
'}';
}
}
public ListNode[] splitListToParts1(ListNode root, int k) {
ListNode[] lists = new ListNode[k];
int len = 0;
for (ListNode p = root; p != null; p = p.next) {
len++;
}
// 计算出每组有多少个元素
int t = (int) Math.ceil((double) len / k);
int m = len % k;
for (int i = 0; i < k && root != null; i++) {
lists[i] = root;
// 这一步j的值,可以考虑下是为什么 奇偶?
for (int j = 1; j < (i < m ? t : m == 0 ? t : t - 1); j++) {
root = root.next;
}
ListNode temp = root.next;
// 这里是做分隔
root.next = null;
root = temp;
}
return lists;
}
public static void main(String[] args) throws InterruptedException {
Solution solution = new Solution();
ListNode head = new ListNode(1);
head.next = new ListNode(2);
head.next.next = new ListNode(3);
head.next.next.next = new ListNode(4);
head.next.next.next.next = new ListNode(5);
head.next.next.next.next.next = new ListNode(6);
head.next.next.next.next.next.next = new ListNode(7);
// head.next.next.next.next.next.next.next = new ListNode(8);
// head.next.next.next.next.next.next.next.next = new ListNode(9);
//print(head);
// head = solution.oddEvenList(head);
solution.splitListToParts1(head, 3);
//print(head);
}
}