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)

相关推荐
CCF_NOI.6 分钟前
(普及−)B3629 吃冰棍——二分/模拟
数据结构·c++·算法
运器1231 小时前
【一起来学AI大模型】支持向量机(SVM):核心算法深度解析
大数据·人工智能·算法·机器学习·支持向量机·ai·ai编程
Zedthm1 小时前
LeetCode1004. 最大连续1的个数 III
java·算法·leetcode
神的孩子都在歌唱1 小时前
3423. 循环数组中相邻元素的最大差值 — day97
java·数据结构·算法
YuTaoShao1 小时前
【LeetCode 热题 100】73. 矩阵置零——(解法一)空间复杂度 O(M + N)
算法·leetcode·矩阵
dying_man2 小时前
LeetCode--42.接雨水
算法·leetcode
vortex53 小时前
算法设计与分析 知识总结
算法
艾莉丝努力练剑3 小时前
【C语言】学习过程教训与经验杂谈:思想准备、知识回顾(三)
c语言·开发语言·数据结构·学习·算法
ZZZS05163 小时前
stack栈练习
c++·笔记·学习·算法·动态规划
黑听人3 小时前
【力扣 困难 C】115. 不同的子序列
c语言·leetcode