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)

相关推荐
__AtYou__3 分钟前
Golang | Leetcode Golang题解之第417题太平洋大西洋水流问题
leetcode·golang·题解
yanyanwenmeng5 分钟前
matlab基础
开发语言·算法·matlab
##晴天小猪7 分钟前
ByteTrack多目标跟踪流程图
人工智能·算法·目标检测·机器学习·目标跟踪
Ddddddd_15818 分钟前
C++ | Leetcode C++题解之第421题数组中两个数的最大异或值
c++·leetcode·题解
ly-how21 分钟前
leetcode练习 二叉树的层序遍历
算法·leetcode
疑惑的杰瑞33 分钟前
[数据结构]算法复杂度详解
c语言·数据结构·算法
大油头儿36 分钟前
排序算法-选择排序
数据结构·算法·排序算法
搞点夜点心42 分钟前
算法课习题汇总(2)
算法
大二转专业1 小时前
408算法题leetcode--第10天
考研·算法·leetcode
.别止步春天.1 小时前
Python中lambda表达式的使用——完整通透版
数据结构·python·算法