前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >LeetCode 61. 旋转链表

LeetCode 61. 旋转链表

原创
作者头像
freesan44
修改2021-09-16 10:42:47
1890
修改2021-09-16 10:42:47
举报
文章被收录于专栏:freesan44freesan44

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

https://leetcode-cn.com/problems/rotate-list/

题目描述

代码语言:txt
复制
给你一个链表的头节点 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:

代码语言:txt
复制
# 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(1)$

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 题目地址(61. 旋转链表)
  • 题目描述
  • 思路
  • 代码
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档