mirror of
https://github.com/autistic-symposium/master-algorithms-py.git
synced 2025-04-29 20:26:07 -04:00
Create rotate_list_by_k.py
This commit is contained in:
parent
18389003c4
commit
d7280726ad
25
linked_lists/rotate_list_by_k.py
Normal file
25
linked_lists/rotate_list_by_k.py
Normal file
@ -0,0 +1,25 @@
|
|||||||
|
#!/usr/bin/env python3
|
||||||
|
# -*- coding: utf-8 -*-
|
||||||
|
# author: bt3gl
|
||||||
|
|
||||||
|
|
||||||
|
def rotate_list_by_k(head, k):
|
||||||
|
|
||||||
|
if head is None and head.next is None:
|
||||||
|
return None
|
||||||
|
|
||||||
|
end, new_end, n = head, head, 1
|
||||||
|
|
||||||
|
while end.next:
|
||||||
|
end = end.next
|
||||||
|
n += 1
|
||||||
|
end.next = head
|
||||||
|
|
||||||
|
for i in range(n - k % n - 1):
|
||||||
|
new_end = new_end.next
|
||||||
|
|
||||||
|
new_head = new_end.next
|
||||||
|
new_end.next = None
|
||||||
|
|
||||||
|
return new_head
|
||||||
|
|
Loading…
x
Reference in New Issue
Block a user