旋转链表

 

 

https://leetcode.cn/problems/rotate-list/solution/xiang-zi-xing-che-lian-yi-yang-qu-xuan-z-di8y/

 

 

/**
 * Definition for singly-linked list.
 * type ListNode struct {
 *     Val int
 *     Next *ListNode
 * }
 */
func rotateRight(head *ListNode, k int) *ListNode {
    if head == nil {
        return nil
    }
    now := head
    num := 1  // 计算链表长度
    for now.Next != nil {
        num ++
        now = now.Next
    }
    now.Next = head //将链表末尾和开头连接形成环
    cnt := num - (k%num) //计算需要移动的步数
    for i := 0; i < cnt; i ++ {
        now = now.Next // 移动
    }
    h := now.Next //获取新链表头部
    now.Next = nil //移除指向新链表头部的指针,也就是拆环
    return h
}

 

posted @ 2022-07-01 16:30  知道了呀~  阅读(59)  评论(0编辑  收藏  举报