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)

相关推荐
qq_4335545415 分钟前
C++ 单调栈
数据结构·c++·算法
向前阿、17 分钟前
数据结构从基础到实战——排序
c语言·开发语言·数据结构·程序人生·算法
2401_8414956441 分钟前
【语音识别】混合高斯模型
人工智能·python·算法·机器学习·语音识别·gmm·混合高斯模型
码上零乱1 小时前
跟着小码学算法Day19:路径总和
java·数据结构·算法
天选之女wow2 小时前
【代码随想录算法训练营——Day53】图论——110.字符串接龙、105.有向图的完全可达性、106.岛屿的周长
算法·深度优先·图论
安迪西嵌入式2 小时前
数据平滑处理算法03——中心移动平均
java·前端·算法
CN-Dust3 小时前
【C++】2025CSP-J第二轮真题及解析
开发语言·c++·算法
贝塔实验室3 小时前
译码器的结构
驱动开发·算法·网络安全·fpga开发·硬件工程·信息与通信·信号处理
夏鹏今天学习了吗3 小时前
【LeetCode热题100(57/100)】括号生成
算法·leetcode·职场和发展
三花聚顶<>3 小时前
310.力扣LeetCode_ 最小高度树_直径法_DFS
算法·leetcode·深度优先