leetcode61. Rotate List

Given the head of a linked list, rotate the list to the right by k places.

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

Input: head = 1,2,3,4,5, k = 2

Output: 4,5,1,2,3

class Solution:

def rotateRight(self, head, k):

if not head or not head.next: return head

求链表长度

_len = 0

cur = head

while cur:

_len += 1

cur = cur.next

对长度取模

k %= _len

if k == 0: return head

让 fast 先向后走 k 步

fast, slow = head, head

while k:

fast = fast.next

k -= 1

此时 slow 和 fast 之间的距离是 k;fast 指向第 k+1 个节点

当 fast.next 为空时,fast 指向链表最后一个节点,slow 指向倒数第 k + 1 个节点

while fast.next:

fast = fast.next

slow = slow.next

newHead 是倒数第 k 个节点,即新链表的头

newHead = slow.next

让倒数第 k + 1 个节点 和 倒数第 k 个节点断开

slow.next = None

让最后一个节点指向原始链表的头

fast.next = head

return newHead

相关推荐
m0_547486665 天前
《数据结构教程》全套 PPT课件2026
数据结构
tryxr6 天前
矩阵的几种基础变换
java·数据结构·算法·矩阵
mmmmath_36 天前
LeetCode.028.找出字符串中第一个匹配项的
数据结构·算法·leetcode
All for pursuit.6 天前
【栈-4】739.每日温度
数据结构·c++·算法·leetcode
All for pursuit.6 天前
【栈-5】84.柱状图中最大的矩形
数据结构·c++·算法·leetcode
渡我白衣6 天前
HttpRequest与HttpResponse的实现
服务器·数据结构·c++·人工智能·tcp/ip·机器学习·caffe
晴天的雨.9926 天前
【C++算法】和为s的两个数
开发语言·数据结构·c++·算法
淡海水6 天前
13-04-面试-源码级深度追问链
数据结构·unity·面试·c#·游戏引擎·源码·il2cpp
Logic1016 天前
C语言/数据结构位运算题解:异或XOR找出时尚聚会中的“独特颜色“——只出现一次的数字
c语言·数据结构·数组·位运算·时间复杂度·算法题·异或性质
2401_839080546 天前
C++常见八股
数据结构·c++·算法