forked from kamyu104/LeetCode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathprint-immutable-linked-list-in-reverse.py
70 lines (61 loc) · 1.68 KB
/
print-immutable-linked-list-in-reverse.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
# Time: O(n)
# Space: O(sqrt(n))
import math
class Solution(object):
def printLinkedListInReverse(self, head):
"""
:type head: ImmutableListNode
:rtype: None
"""
def print_nodes(head, count):
nodes = []
while head and len(nodes) != count:
nodes.append(head)
head = head.getNext()
for node in reversed(nodes):
node.printValue()
count = 0
curr = head
while curr:
curr = curr.getNext()
count += 1
bucket_count = int(math.ceil(count**0.5))
buckets = []
count = 0
curr = head
while curr:
if count % bucket_count == 0:
buckets.append(curr)
curr = curr.getNext()
count += 1
for node in reversed(buckets):
print_nodes(node, bucket_count)
# Time: O(n)
# Space: O(n)
class Solution2(object):
def printLinkedListInReverse(self, head):
"""
:type head: ImmutableListNode
:rtype: None
"""
nodes = []
while head:
nodes.append(head)
head = head.getNext()
for node in reversed(nodes):
node.printValue()
# Time: O(n^2)
# Space: O(1)
class Solution3(object):
def printLinkedListInReverse(self, head):
"""
:type head: ImmutableListNode
:rtype: None
"""
tail = None
while head != tail:
curr = head
while curr.getNext() != tail:
curr = curr.getNext()
curr.printValue()
tail = curr