-
Notifications
You must be signed in to change notification settings - Fork 90
/
Rotate List.py
53 lines (40 loc) · 1022 Bytes
/
Rotate List.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
"""
Given a list, rotate the list to the right by k places, where k is non-negative.
Example
Given 1->2->3->4->5 and k = 2, return 4->5->1->2->3.
"""
__author__ = 'Daniel'
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def rotateRight(self, head, k):
if not head:
return head
dummy = ListNode(0)
dummy.next = head
l = self.get_len(head)
k %= l # pitfall, ask to clarify k
pre = dummy
i = 0
while pre and i < l-k:
pre = pre.next
i += 1
new_head = pre.next
if not new_head:
return dummy.next
cur = new_head
pre.next = None
while cur.next:
cur = cur.next
cur.next = dummy.next
dummy.next = new_head
return dummy.next
def get_len(self, head):
l = 0
cur = head
while cur:
l += 1
cur = cur.next
return l