乐趣区

关于go:Leetcode专题25K-个一组翻转链表

力扣链接:
https://leetcode.cn/problems/reverse-nodes-in-k-group/
解题思路:
通过递归实现的,每次递归将以后链表的前 k 个节点进行翻转,并将翻转后的链表的尾节点连贯上递归后返回的链表的头节点,最终返回整个链表的新头节点

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

func reverse(start, end *ListNode) *ListNode {
    var pre *ListNode
    cur := start
    for cur != end {
        nxt := cur.Next
        cur.Next = pre
        pre = cur
        cur = nxt
    }
    return pre
}
退出移动版