24. Leetcode 61. 旋转链表 (链表-基础操作类-旋转链表)
生活随笔
收集整理的這篇文章主要介紹了
24. 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]思路:首先找到舊的尾部并將其與鏈表頭相連(cur.next = head),整個鏈表閉合成環,同時計算出鏈表的長度 n。然后找到新的尾部, 第 n - k % n - 1 個節點 ,新的鏈表頭是第 n - k % n 個節點。最后斷 開環 end.next = None,并返回新的鏈表頭 new_head。# 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 head == None:return headif head.next == None:return head# 找到鏈表表尾cur = headn = 1while cur.next != None:cur = cur.nextn += 1cur.next = head# 找到斷開的節點end = headfor _ in range(n-k%n-1):end = end.nextnew_head = end.nextend.next = Nonereturn new_head
總結
以上是生活随笔為你收集整理的24. Leetcode 61. 旋转链表 (链表-基础操作类-旋转链表)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 23. Leetcode 24. 两两交
- 下一篇: 25. Leetcode 143. 重排