-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathRotate List.py
71 lines (51 loc) · 1.52 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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
# Time complexity - O(N+k)
# Space complexity - O(N)
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def rotateRight(self, head: Optional[ListNode], k: int) -> Optional[ListNode]:
from collections import deque
if head is None:
return None
queue = deque()
ptr = head
while ptr:
queue.append(ptr.val)
ptr = ptr.next
while k > 0:
item = queue.pop()
queue.appendleft(item)
k = k-1
ptr = head = None
for i in range(len(queue)):
if head is None:
head = ListNode(queue[i])
ptr = head
else:
ptr.next = ListNode(queue[i])
ptr = ptr.next
return head
# Time complexity - O(N)
# Space complexity - O(1)
class Solution:
def rotateRight(self, head: Optional[ListNode], k: int) -> Optional[ListNode]:
if head is None or k == 0 or head.next is None:
return head
slow = fast = ptr = head
count = 0
while ptr:
count += 1
ptr = ptr.next
k = k % count
for _ in range(k):
fast = fast.next
while fast.next:
fast = fast.next
slow = slow.next
temp = slow.next
fast.next = head
slow.next = None
return temp if k != 0 else head