Skip to content

Commit 69e4b75

Browse files
committed
added rotate_list.py
1 parent 504c5d7 commit 69e4b75

File tree

1 file changed

+59
-0
lines changed

1 file changed

+59
-0
lines changed

python/datastructures/rotate_list.py

Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,59 @@
1+
class ListNode:
2+
def __init__(self, val=0, next=None):
3+
self.val = val
4+
self.next = next
5+
6+
def __str__(self):
7+
root = self
8+
arr = []
9+
10+
while root:
11+
arr.append(root.val)
12+
root = root.next
13+
14+
return str(arr)
15+
16+
17+
def rotate_right(lst: ListNode, k: int) -> ListNode:
18+
if lst is None:
19+
return None
20+
if lst.next is None:
21+
return lst
22+
23+
k %= get_length(lst)
24+
25+
for _ in range(k):
26+
lst = rotate_r(lst)
27+
28+
return lst
29+
30+
def rotate_r(lst):
31+
root = lst
32+
33+
while root.next.next:
34+
root = root.next
35+
36+
root.next.next = lst
37+
l2 = root.next
38+
root.next = None
39+
40+
return l2
41+
42+
def get_length(lst: ListNode) -> int:
43+
l = 0
44+
copy = lst
45+
46+
while copy.next:
47+
l += 1
48+
copy = copy.next
49+
50+
return l+1
51+
52+
53+
54+
55+
56+
if __name__ == "__main__":
57+
lst = ListNode(1, ListNode(2, ListNode(3, ListNode(4, ListNode(5)))))
58+
59+
print(rotate_right(lst, 222223))

0 commit comments

Comments
 (0)