First we have to know the length of list, say n, then k = k % n. And then cut the list into two parts and put them back together.
Solution:
# T:O(n) S:O(1)
class Solution:
# @param head, a ListNode
# @param k, an integer
# @return a ListNode
def rotateRight(self, head, k):
if k == 0 or head == None:
return head
dummy = ListNode(0)
dummy.next, p, count = head, dummy, 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
Run Time: 68 ms
No comments:
Post a Comment