-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path61.py
77 lines (64 loc) · 1.58 KB
/
61.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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
# Definition for singly-linked list.
class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
class Lists(object):
def __init__(self, l):
if len(l)==0:
self.head = None
else:
self.head = ListNode(l[0])
if len(l) > 0:
cur = self.head
for i in xrange(1, len(l)):
cur.next = ListNode(l[i])
cur = cur.next
def returnHead(self):
return self.head
def showList(self):
cur = self.head
if not cur:
return None
while cur.next:
print cur.val, '->',
cur = cur.next
print cur.val
class Solution(object):
def rotateRight(self, head, k):
"""
:type head: ListNode
:type k: int
:rtype: ListNode
"""
n = 1
cur = head
if not cur:
return None
while cur.next:
cur = cur.next
n += 1
n = n - k%n
# print n
cur.next = head
cur = head
# print cur.val
while n>1 and cur.next:
cur = cur.next
n -= 1
# print cur.val
head = cur.next
cur.next = None
return head
if __name__ == '__main__':
li = Lists([1,2,3,4,5])
li.showList()
solution = Solution()
test = li.returnHead()
l = solution.rotateRight(li.returnHead(), 1)
cur = l
if cur:
while cur.next:
print cur.val, '->',
cur = cur.next
print cur.val