-
Notifications
You must be signed in to change notification settings - Fork 0
/
RotateList.py
54 lines (45 loc) · 1.17 KB
/
RotateList.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
52
53
54
# Problem: https://leetcode.com/problems/rotate-list/description/
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def rotateRight(self, head, k):
"""
:type head: ListNode
:type k: int
:rtype: ListNode
"""
if head == None:
return None
curr = head
n = 0
while(curr):
curr = curr.next
n += 1
k = k%n
if k == 0:
return head
dummy = ListNode(0)
curr = head
dummy.next = head
prev = dummy
end = dummy
while(k):
if not curr:
curr = head
end = dummy
curr = curr.next
end = end.next
k -= 1
start = head
while (curr != None):
curr = curr.next
end = end.next
start = start.next
prev = prev.next
prev.next = end.next
end.next = head
head = start
return head