Skip to content

Commit 7643379

Browse files
authored
Create print-immutable-linked-list-in-reverse.cpp
1 parent 714e3ab commit 7643379

File tree

1 file changed

+71
-0
lines changed

1 file changed

+71
-0
lines changed
Lines changed: 71 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,71 @@
1+
// Time: O(n)
2+
// Space: O(sqrt(n))
3+
4+
class Solution {
5+
public:
6+
void printLinkedListInReverse(ImmutableListNode* head) {
7+
int count = 0;
8+
auto curr = head;
9+
while (curr) {
10+
curr = curr->getNext();
11+
++count;
12+
}
13+
int bucket_count = ceil(sqrt(count));
14+
15+
vector<ImmutableListNode *> buckets;
16+
count = 0;
17+
curr = head;
18+
while (curr) {
19+
if (count % bucket_count == 0) {
20+
buckets.emplace_back(curr);
21+
}
22+
curr = curr->getNext();
23+
++count;
24+
}
25+
26+
for (int i = buckets.size() - 1; i >= 0; --i) {
27+
printNodes(buckets[i], bucket_count);
28+
}
29+
}
30+
31+
private:
32+
void printNodes(ImmutableListNode *head, int count) {
33+
vector<ImmutableListNode *> nodes;
34+
while (head && nodes.size() != count) {
35+
nodes.emplace_back(head);
36+
head = head->getNext();
37+
}
38+
for (int i = nodes.size() - 1; i >= 0; --i) {
39+
nodes[i]->printValue();
40+
}
41+
}
42+
};
43+
44+
// Time: O(n)
45+
// Space: O(n)
46+
class Solution2 {
47+
public:
48+
void printLinkedListInReverse(ImmutableListNode* head) {
49+
vector<ImmutableListNode *> nodes;
50+
while (head) {
51+
nodes.emplace_back(head);
52+
head = head->getNext();
53+
}
54+
for (int i = nodes.size() - 1; i >= 0; --i) {
55+
nodes[i]->printValue();
56+
}
57+
}
58+
};
59+
60+
61+
// Time: O(n^2)
62+
// Space: O(1)
63+
class Solution3 {
64+
public:
65+
void printLinkedListInReverse(ImmutableListNode* head) {
66+
for (ImmutableListNode *tail = nullptr, *curr = nullptr; tail != head; tail = curr) {
67+
for (curr = head; curr->getNext() != tail; curr = curr->getNext());
68+
curr->printValue();
69+
}
70+
}
71+
};

0 commit comments

Comments
 (0)