LeetCode 61. 旋转链表

LeetCode 61. 旋转链表

给你一个链表的头节点 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

python 复制代码
# 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 k == 0 or not head or not head.next:
            return head
        
        _head = head
        total = 0
        while _head:
            total += 1
            _head = _head.next
        _k = k % total

        if _k == 0:
            return head

        dummy = ListNode(next=head)
        slow = fast = dummy
        while fast.next:
            if _k < 1:
                slow = slow.next
            fast = fast.next
            _k -= 1

            
        first = slow.next
        slow.next = None  # forth
        second = fast
        third = dummy.next
        dummy.next = first
        second.next = third
        
        return dummy.next

时间复杂度O(n)

空间复杂度O(1)

看了一眼官解,发现是先连成环然后再断开,比上面的思路时间复杂度常数更小,Python 实现如下

python 复制代码
# 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 k == 0 or not head or not head.next:
            return head

        _head = head
        total = 1
        while _head.next:
            total += 1
            _head = _head.next
        _head.next = head

        count = total - k % total
        while count:
            _head = _head.next
            count -= 1
        
        res = _head.next
        _head.next = None
        return res

时间复杂度O(n)

空间复杂度O(1)

相关推荐
8Qi89 小时前
回文子串(Palindromic Substrings)—— 题解
算法·leetcode·职场和发展·动态规划
小宋加油啊14 小时前
机械臂抓取物体 PVN3D算法调研学习
学习·算法·3d
lqqjuly14 小时前
前沿算法深度解析(一)
算法
小欣加油14 小时前
leetcode1926 迷宫中离入口最近的出口
数据结构·c++·算法·leetcode·职场和发展
happymaker062616 小时前
LeetCodeHot100——42.接雨水
算法
阿正的梦工坊17 小时前
【Rust】07-错误处理:Option、Result 与 ? 运算符
开发语言·算法·rust
努力努力再努力wz18 小时前
【内存管理与高并发内存池系列】从 mmap 到 malloc:文件映射、匿名映射与 glibc 内存分配机制详解
linux·c语言·数据结构·数据库·c++·qt·链表
八解毒剂18 小时前
数据结构-平衡二叉树——对二叉搜索树的优化
数据结构·c++·算法
运行时记录19 小时前
别再手动写提示词了 — SkillOpt 让技能文档自己进化
算法