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

相关推荐
vvilkim4 小时前
数据结构类型、区别与应用场景:一篇讲透选型逻辑
数据结构
阿卡好可爱9 小时前
Lua 热更新不生效:改完文件线上仍是旧逻辑,package.loaded 与 upvalue 重绑定详解
数据结构·分布式·后端·架构·lua
心仪久了会沦陷1 天前
C语言数据结构入门——树与二叉树详解:概念、堆实现与链式遍历
c语言·数据结构·算法
码少女1 天前
数据结构——图的基础
数据结构
Severus_black1 天前
【C++初阶】list使用及相关实现,思路顺滑流畅!
c语言·数据结构·c++·stl·list
二本咕咕-机械转码1 天前
FreeRTOS深入解析(八)IPC机制之FromISR详解
数据结构·单片机·链表
1-1=01 天前
C# 数据结构和特殊类型
数据结构·c#·.net·.netcore
希和20271 天前
C语言程序设计题|有序数组插入数字冒泡排序
c语言·数据结构·算法
布莱克6052 天前
C++ 中 map 的 insert 与 emplace:key 已存在时会覆盖吗?
开发语言·数据结构·c++·算法·map
D e re k ZH2 天前
C++ 系统学习手记:从语法细节到工程实践
开发语言·数据结构·c++·算法