-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathrotate_list.py
52 lines (37 loc) · 1.07 KB
/
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
52
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
# @param A : head node of linked list
# @param B : integer
# @return the head node in the linked list
def rotateRight(self, A, B):
nA = 0
K = A
while K:
nA += 1
K = K.next
if nA <= 1:
return A
start = nA - B
start = start % nA
prev = None
K = A
prev=None
while K and start >= 0:
if start == 0:
if prev:
prev.next = None
else:
return K
break
start -= 1
prev = K
K = K.next
head = K
while K.next:
K = K.next
K.next = A
return head