題目出處
難度
medium
個人範例程式碼
# 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: Optional[ListNode], k: int) -> Optional[ListNode]:
if not head or k == 0:
return head
cur = head
length = 0
while(cur):
length += 1
prev = cur
cur = cur.next
else:
prev.next = head # circular
k = length - (k % length) # counterclockwise -> clockwise
while(k > 0): # move k times (clockwise)
k -= 1
prev = head
head = head.next
else:
prev.next = None # tail
return head # head
最近在練習程式碼本身就可以自解釋的 Coding style,可以嘗試直接閱讀程式碼理解
算法說明
網路上看到覺得最漂亮的算法,
既然都要 rotate 了,不如直接先串成一個環吧!
注意 rotate 逆時針
從題目敘述我們會發現 rotate 方向為「逆時針」,
這樣我們就有必要先計算總共有幾個元素,
再來透過 k = k - (k % length),我們就可以得到「順時針要走多少 k 」
input handling
如果沒有 input head,return head
Boundary conditions
while loop 控制 k 的搜尋範圍,
先弄成環之後,處理環的前後。