其他分享
首页 > 其他分享> > leetcode:K 个一组翻转链表(没弄懂)

leetcode:K 个一组翻转链表(没弄懂)

作者:互联网

在这里插入图片描述
思路:
1.递归,每次处理k个,不足k个不处理
2.对k个的处理用reverse进行
3.reverse实际上由k+1个,通过prev,first和temp来逐次挪动

src

/**
 * Definition for singly-linked list.
 * type ListNode struct {
 *     Val int
 *     Next *ListNode
 * }
 */
func reverseKGroup(head *ListNode, k int) *ListNode {
    node := head
    for i := 0; i < k; i++ {
        if node == nil {
            return head
        }
        node = node.Next
    }
    newHead := reverse(head, node)
    head.Next = reverseKGroup(node, k)
    return newHead

}

func reverse(first, last *ListNode) *ListNode {
    prev := last
    for first != last {
        tmp := first.Next
        first.Next = prev
        prev = first
        first = tmp
    }
    return prev
}

总结:
思路get了,细节没get

标签:node,head,ListNode,弄懂,Next,链表,prev,leetcode,first
来源: https://blog.csdn.net/weixin_40986490/article/details/120734226