-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrotate_list.py
More file actions
87 lines (68 loc) · 1.56 KB
/
rotate_list.py
File metadata and controls
87 lines (68 loc) · 1.56 KB
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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
from collections import deque
from typing import Optional, Self
class ListNode:
def __init__(self, val: int = 0, next: Self = None):
self.val = val
self.next = next
#não duplica memória mas dá pra melhorar
def rotateRight(head: Optional[ListNode], k: int) -> Optional[ListNode]:
if not head:
return None
node = head
n = 0
while node:
n += 1
node = node.next
k = k % n
if k == 0:
return head
replacer_node = head
queue = deque()
steps = 0
while steps < k:
queue.append(replacer_node.val)
replacer_node = replacer_node.next
steps += 1
start = replacer_node
while replacer_node.next != start:
queue.append(replacer_node.val)
replacer_node.val = queue.popleft()
replacer_node = replacer_node.next
if not replacer_node:
replacer_node = head
replacer_node.val = queue.popleft()
return head
#uso de memória duplicada
def rotateRightV2(head: Optional[ListNode], k: int) -> Optional[ListNode]:
if not head:
return None
node = head
queue = deque()
while node:
queue.append(node.val)
node = node.next
node = head
queue.rotate(k)
while queue:
node.val = queue.popleft()
node = node.next
return
#não usa memória, é rápido e simples
def rotateRightV3(head: Optional[ListNode], k: int) -> Optional[ListNode]:
if not head or not head.next or k == 0:
return head
tail = head
n = 1
while tail.next:
tail = tail.next
n += 1
k = k % n
if k == 0:
return head
tail.next = head
new_tail = head
for _ in range(n - k - 1):
new_tail = new_tail.next
new_head = new_tail.next
new_tail.next = None
return new_head