共计 518 个字符,预计需要花费 2 分钟才能阅读完成。
力扣链接:
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
}
正文完