美文网首页
Split Linked List in Parts

Split Linked List in Parts

作者: 余启涛 | 来源:发表于2019-03-19 22:35 被阅读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
}

相关文章

网友评论

      本文标题:Split Linked List in Parts

      本文链接:https://www.haomeiwen.com/subject/qzmomqtx.html