LeetCode 61. 旋转链表

144 阅读1分钟

题目地址(61. 旋转链表)

leetcode-cn.com/problems/ro…

题目描述

给你一个链表的头节点 head ,旋转链表,将链表每个节点向右移动 k 个位置。

 

示例 1:

输入:head = [1,2,3,4,5], k = 2
输出:[4,5,1,2,3]


示例 2:

输入:head = [0,1,2], k = 4
输出:[2,0,1]


 

提示:

链表中节点的数目在范围 [0, 500] 内
-100 <= Node.val <= 100
0 <= k <= 2 * 109

思路

通过双指针,先把整个链表形成一个循环,然后计算移动到k步之后的链头,断开循环,形成新的链表

代码

  • 语言支持:Python3

Python3 Code:


# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution:
    def rotateRight(self, head: Optional[ListNode], k: int) -> Optional[ListNode]:
        if head  == None:
            return head
        headPoint = head
        length = 1
        while head.next != None:
            head = head.next
            length += 1
        endPoint = head
        endPoint.next = headPoint #形成一个循环
        moveLength = length - (k % length) - 1 #得出移动步数
        print(moveLength)
        while moveLength != 0:
            headPoint = headPoint.next
            moveLength -= 1
        endPoint = headPoint
        headPoint = headPoint.next
        endPoint.next = None
        return headPoint

复杂度分析

令 n 为数组长度。

  • 时间复杂度:O(n)O(n)
  • 空间复杂度:O(1)O(1)