leetcode Rotate list (連結串列旋轉)的python實現
阿新 • • 發佈:2019-01-08
題目如下:
Given a list, rotate the list to the right by k places, where k is non-negative.
For example:
Given 1->2->3->4->5->NULL
and k = 2
,
return 4->5->1->2->3->NULL
.
題目解釋:
給定一個連結串列,將連結串列末尾的k個結點移動到最前面。
思路:
採用 fast-slow 指標的方法,令fast指標先移動k步,步長為1。然後兩個指標同時移動,當fast指標到達最末尾時,將fast指向head,slow指向None,則完成旋轉。
注:題目中的k有可能大於連結串列總長度,因此需要對k取模。
class Solution(object): def rotateRight(self, head, k): if not head or not head.next or k==0: return head ListLen = 0 p = head while(p): ListLen+=1 p = p.next k = k%ListLen if k==0: return head p = head while(k>0): k -=1 p = p.next slow = head fast = p while fast.next: slow = slow.next fast = fast.next new_head = slow.next fast.next = head slow.next = None return new_head