https://leetcode-cn.com/problems/rotate-list/
给你一个链表的头节点 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 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 为数组长度。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。