题目来源
725. 分隔链表
题目描述
题目解析
生成新链表
public static ListNode[] splitListToParts(ListNode root, int k) {
ListNode[] listNodes = new ListNode[k];
if (k <= 1){
return listNodes;
}
int length = 0;
ListNode cur = root;
while (cur != null){
length++;
cur = cur.next;
}
int n = length / k;
int y = length % k;
cur = root;
int x = 0;
while (cur != null){
ListNode s = new ListNode(-1);
ListNode t = s;
for (int i = 0;i < n; i++){
t.next = new ListNode(cur.val);
t = t.next;
cur = cur.next;
}
if (y > 0){
t.next = new ListNode(cur.val);
t = t.next;
cur = cur.next;
y--;
}
listNodes[x++]= s.next;
}
return listNodes;
}
旧链表上的断链操作
public static ListNode[] splitListToParts(ListNode root, int k) {
ListNode[] listNodes = new ListNode[k];
if (k <= 1){
return listNodes;
}
int length = 0;
ListNode cur = root;
while (cur != null){
length++;
cur = cur.next;
}
int n = length / k;
int y = length % k;
cur = root;
for (int x = 0; x < k; x++){
listNodes[x]= cur;
int cLength = n;
if (y > 0){
cLength = cLength + 1;
y--;
}
for (int i = 0; i < cLength - 1; i++){
cur = cur.next;
}
ListNode t = cur.next;
cur.next = null;
cur = t;
}
return listNodes;
}