Skip to content

Commit 20f05af

Browse files
authored
Create print-immutable-linked-list-in-reverse.py
1 parent 7643379 commit 20f05af

File tree

1 file changed

+70
-0
lines changed

1 file changed

+70
-0
lines changed
Lines changed: 70 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,70 @@
1+
# Time: O(n)
2+
# Space: O(sqrt(n))
3+
4+
import math
5+
6+
7+
class Solution(object):
8+
def printLinkedListInReverse(self, head):
9+
"""
10+
:type head: ImmutableListNode
11+
:rtype: None
12+
"""
13+
def print_nodes(head, count):
14+
nodes = []
15+
while head and len(nodes) != count:
16+
nodes.append(head)
17+
head = head.getNext()
18+
for node in reversed(nodes):
19+
node.printValue()
20+
21+
count = 0
22+
curr = head
23+
while curr:
24+
curr = curr.getNext()
25+
count += 1
26+
bucket_count = int(math.ceil(count**0.5))
27+
28+
buckets = []
29+
count = 0
30+
curr = head
31+
while curr:
32+
if count % bucket_count == 0:
33+
buckets.append(curr)
34+
curr = curr.getNext()
35+
count += 1
36+
for node in reversed(buckets):
37+
print_nodes(node, bucket_count)
38+
39+
40+
# Time: O(n)
41+
# Space: O(n)
42+
class Solution2(object):
43+
def printLinkedListInReverse(self, head):
44+
"""
45+
:type head: ImmutableListNode
46+
:rtype: None
47+
"""
48+
nodes = []
49+
while head:
50+
nodes.append(head)
51+
head = head.getNext()
52+
for node in reversed(nodes):
53+
node.printValue()
54+
55+
56+
# Time: O(n^2)
57+
# Space: O(1)
58+
class Solution3(object):
59+
def printLinkedListInReverse(self, head):
60+
"""
61+
:type head: ImmutableListNode
62+
:rtype: None
63+
"""
64+
tail = None
65+
while head != tail:
66+
curr = head
67+
while curr.getNext() != tail:
68+
curr = curr.getNext()
69+
curr.printValue()
70+
tail = curr

0 commit comments

Comments
 (0)