Leetcode 61 旋转链表 (每日一题 20210723)
生活随笔
收集整理的這篇文章主要介紹了
Leetcode 61 旋转链表 (每日一题 20210723)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
給你一個鏈表的頭節點 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]鏈接:https://leetcode-cn.com/problems/rotate-listclass Solution:def rotateRight(self, head:ListNode, k:int):if not head or not head.next:return headlength = 0cur = headwhile cur:length += 1cur = cur.nextk = k%lengthif k==0:return headslow, fast = head, headwhile fast.next:slow = slow.nextfast = fast.nextNewhead = slow.nextslow.next = Nonefast.next = headreturn Newhead
總結
以上是生活随笔為你收集整理的Leetcode 61 旋转链表 (每日一题 20210723)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Leetcode 23 合并k个升序链表
- 下一篇: Leetcode 92 反转链表 II