zoukankan      html  css  js  c++  java
  • LeetCode 61. 旋转链表

    61. 旋转链表

    Difficulty: 中等

    给你一个链表的头节点 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 * 10<sup>9</sup>

    Solution

    将题目分解为三步,第一步拿到链表旋转后的前半段pre,第二步拿到链表旋转的后半段pos,第三步把链表的前半段放在链表后半段的后面。

    题目要求是将链表的每个节点向右移动k个位置,k有可能会大于链表的长度l,那么意味着链表前半段的长度distancel - k % l,遍历链表移动distance长度获得前半段pre,剩余的部分为链表的后半段pos,取出后半段之后指向前半段就解决了。

    # 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: ListNode, k: int) -> ListNode:
            if not head or not k:
                return head
            t, l = head, 0
            while t:
                l += 1
                t = t.next
            distance = l - k % l
            
            pre = ListNode(-1)
            p = pre
            while distance > 0:
                curNode = ListNode(head.val)
                p.next = curNode
                p = p.next
                head = head.next
                distance -= 1
            p.next = None
            
            res = ListNode(-1)
            pos = res
            while head:
                curNode = ListNode(head.val)
                pos.next = curNode
                pos = pos.next
                head = head.next
            pos.next = pre.next
            return res.next
    
  • 相关阅读:
    C# 16进制字节转Int(涉及:Base64转byte数组)
    c# CRC-16 / MODBUS 校验计算方法 及 异或校验算法
    SqlSugar 用法大全
    SQL Server-聚焦NOLOCK、UPDLOCK、HOLDLOCK、READPAST你弄懂多少?
    使用 tabindex 配合 focus-within 巧妙实现父选择器
    DataX 3.0 源码解析一
    Golang必备技巧:接口型函数
    PID控制
    dockerfile,拷贝文件夹到镜像中(不是拷贝文件夹中的内容到镜像)
    什么是PKI?主要作用是什么?
  • 原文地址:https://www.cnblogs.com/swordspoet/p/14585439.html
Copyright © 2011-2022 走看看