-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrotate_linked_list.py
More file actions
43 lines (32 loc) · 842 Bytes
/
Copy pathrotate_linked_list.py
File metadata and controls
43 lines (32 loc) · 842 Bytes
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
from collections import deque
# Definition for singly-linked list.
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
# Definition for singly-linked list.
class ListNode(object):
def __init__(self, val=0, next=None):
self.val = val
self.next = next
def rotateRight(head, k):
if not head or k == 0:
return head
length = 1
tail = head
while tail.next:
tail = tail.next
length += 1
k = k % length
if k == 0:
return head
tail.next = head # Make it circular
steps_to_new_head = length - k
new_tail = tail
while steps_to_new_head:
new_tail = new_tail.next
steps_to_new_head -= 1
new_head = new_tail.next
new_tail.next = None
return new_head
print(rotateRight())