LeetCode725. 分隔链表
1. 问题描述
2. 思路
3. 代码
/**
* Definition for singly-linked list.
* type ListNode struct {
* Val int
* Next *ListNode
* }
*/
func splitListToParts(head *ListNode, k int) []*ListNode {
length := 0
for node := head; node != nil ; node = node.Next {
length++
}
counter, firstCounter := length / k, length % k
res := make([]*ListNode, k)
for i, cur := 0, head; i < k && cur != nil ; i++ {
res[i] = cur
resSize := counter
if i < firstCounter {
resSize++
}
for j := 1; j < resSize; j++ {
cur = cur.Next
}
cur, cur.Next = cur.Next, nil
}
return res
}