File tree Expand file tree Collapse file tree 1 file changed +70
-0
lines changed Expand file tree Collapse file tree 1 file changed +70
-0
lines changed Original file line number Diff line number Diff line change
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
You can’t perform that action at this time.
0 commit comments