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
    
  • 相关阅读:
    iOS 获取全局唯一标示符
    iOS 获取全局唯一标示符
    如何让UIViewController自动弹出PickerView
    如何让UIViewController自动弹出PickerView
    防止NSTimer和调用对象之间的循环引用
    防止NSTimer和调用对象之间的循环引用
    inputAccessoryView,inputView
    @encode关键字
    @encode关键字
    用 Flask 来写个轻博客 (11) — M(V)C_创建视图函数
  • 原文地址:https://www.cnblogs.com/swordspoet/p/14585439.html
Copyright © 2011-2022 走看看