原題地址:https://oj.leetcode.com/problems/rotate-list/
題意:
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=2,(1,2,3,4,5)循環右移兩位變為(4,5,1,2,3)。由於k值有可能比鏈表長度大很多,所以先要用一個count變量求出鏈表的長度。而k%count就是循環右移的步數。
代碼:
# Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: # @param head, a ListNode # @param k, an integer # @return a ListNode def rotateRight(self, head, k): if k == 0: return head if head == None: return head dummy = ListNode(0) dummy.next = head p = dummy count = 0 while p.next: p = p.next count += 1 p.next = dummy.next step = count - ( k % count ) for i in range(0, step): p = p.next head = p.next p.next = None return head