k个一组链表翻转

 

 https://leetcode.cn/problems/reverse-nodes-in-k-group/

 

func main(){
    h:=newList()
    ans:=reverseKGroup(h,3)
    for ans!=nil{
        fmt.Println(ans.Val)
        ans=ans.Next
    }

}
func newList() *ListNode{
    head:=&ListNode{}
    for i:=0;i<6;i++{
        tmp:=&ListNode{
            Val:  i,
            Next: nil,
        }
        //头插法
        tmp.Next=head
        head=tmp
    }
    return head
}
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
}

 

posted @ 2022-06-17 15:15  知道了呀~  阅读(56)  评论(0编辑  收藏  举报