-
Notifications
You must be signed in to change notification settings - Fork 10
/
Copy path61.Rotate-List.py
48 lines (40 loc) · 1001 Bytes
/
61.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
# https://leetcode.com/problems/rotate-list/
#
# algorithms
# Medium (26.09%)
# Total Accepted: 169,600
# Total Submissions: 650,019
# 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
"""
length = 0
tmp = head
tail = None
while tmp:
length += 1
tail = tmp
tmp = tmp.next
if length == 0:
return head
k %= length
if k == 0:
return head
tmp = head
pre = None
for _ in xrange(length - k):
pre = tmp
tmp = tmp.next
res = ListNode(-1)
res.next = tmp
pre.next = None
tail.next = head
return res.next