【LeetCode每天一題】Rotate List(旋轉鏈表)
阿新 • • 發佈:2019-04-22
type etc exp 直接 style info back 結果 null
Given a linked list, rotate the list to the right by k places, where k is non-negative.
Example 1:
Input: 1->2->3->4->5->NULL, k = 2 Output: 4->5->1->2->3->NULL Explanation: rotate 1 steps to the right: 5->1->2->3->4->NULL rotate 2 steps to the right: 4->5->1->2->3->NULL
Example 2:Input: 0->1->2->NULL, k = 4 Output: 2->0->1->NULL
思路
對於鏈表類的題目最重要的就是指針的控制,因此對於這道題我的思路就是我們先找到倒數第K個節點前一個節點的位置,並先將鏈表尾部指針指向頭指針,然
後將頭指針指向倒數第K個節點,最後對倒數K節點上一個指針賦值為None。時間復雜度為O(n), 空間復雜度為O(1)
圖示步驟
解決代碼
1 class Solution(object):
2 def rotateRight(self, head, k):
3 """
4 :type head: ListNode
5 :type k: int
6 :rtype: ListNode
7 """
8 if not head or k < 0: # 為空或者K小於0直接返回
9 return head
10 length, tem = 0, head
11
12 while tem: # 求出鏈表的長度
13 tem, length = tem.next, length + 1
14
15 k = k % length # 防止K的長度大於鏈表的長度
16 fast, slow = head, head
17 while k > 0: # 快指針先走K步
18 fast, k = fast.next, k-1
19
20 while fast.next: # 兩個指針同時動
21 slow, fast = slow.next, fast.next
22 fast.next = head # 進行指針交換操作得到結果
23 head = slow.next
24 slow.next = None
25 return head
26
【LeetCode每天一題】Rotate List(旋轉鏈表)