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
.
Subscribe to see which companies asked this question
先算出list的长度,然后再用最朴素的想法来完成
class Solution(object):
def rotateRight(self, head, k):
if k == 0 or head == None:
return head
if not head.next:
return head
h = head
l = 0
while h:
l += 1
tail = h
h = h.next
#print l
k = k % l
if k == 0:
return head
count = 0
h = head
new_h = ListNode(0)
while count < l - k:
prv = h
h = h.next
count += 1
new_h.next = h
tail.next = head
prv.next = None
return new_h.next