Split Linked List in Parts
2019-03-19 本文已影响0人
余启涛
题目.png
解决思路
直接求出链表长度,除以k得到每个链表长度d,同样求出余数a,即前a个元素长度为d+1,遍历链表分割即可。
/**
* Definition for singly-linked list.
* type ListNode struct {
* Val int
* Next *ListNode
* }
*/
func splitListToParts(root *ListNode, k int) []*ListNode {
count := 0
for cur := root; cur != nil; cur = cur.Next {
count ++
}
a := count / k
b := count % k
list := make([]*ListNode, 0, k)
for cur, i := root, 0; i < k; i++ {
length := a
if b > 0 {
length ++
b --
}
var previous *ListNode = nil
list = append(list, cur)
for j := 0; j < length; j++{
if j == length - 1 {
previous = cur
}
cur = cur.Next
}
if previous != nil {
previous.Next = nil
}
}
return list
}