Leetcode61. 旋转链表

Leetcode61. 旋转链表

1. 问题描述

Leetcode61. 旋转链表
Leetcode61. 旋转链表
Leetcode61. 旋转链表

思路

双指针,右指针先走k个位置,再同时移动左指针和右指针,当右指针指向最后一个节点时,左指针指向倒数第k个节点的前一个节点。

修改对应指针的指向即可

代码

/**
 * Definition for singly-linked list.
 * type ListNode struct {
 *     Val int
 *     Next *ListNode
 * }
 */
func rotateRight(head *ListNode, k int) *ListNode {
    if head == nil {
        return nil
    }

    left, right := head, head
    temp, length := head, 1

    // 计算链表长度
    for temp.Next != nil {
        temp = temp.Next
        length++
    }
    
    // 找链表倒数第k个位置
    for i := 0; i < k % length; i++ {
        right = right.Next
    }

   
    for right.Next != nil {
        right = right.Next
        left = left.Next        // left指向倒数第k个节点,前面一个
    }
    right.Next = head
    newHead := left.Next
    left.Next = nil
    
    return newHead
}
上一篇:工作流模式-工作流异常处理模式


下一篇:树-对称的二叉树