forked from kamyu104/LeetCode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathprint-immutable-linked-list-in-reverse.cpp
70 lines (64 loc) · 1.76 KB
/
print-immutable-linked-list-in-reverse.cpp
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))
class Solution {
public:
void printLinkedListInReverse(ImmutableListNode* head) {
int count = 0;
auto curr = head;
while (curr) {
curr = curr->getNext();
++count;
}
int bucket_count = ceil(sqrt(count));
vector<ImmutableListNode *> buckets;
count = 0;
curr = head;
while (curr) {
if (count % bucket_count == 0) {
buckets.emplace_back(curr);
}
curr = curr->getNext();
++count;
}
for (int i = buckets.size() - 1; i >= 0; --i) {
printNodes(buckets[i], bucket_count);
}
}
private:
void printNodes(ImmutableListNode *head, int count) {
vector<ImmutableListNode *> nodes;
while (head && nodes.size() != count) {
nodes.emplace_back(head);
head = head->getNext();
}
for (int i = nodes.size() - 1; i >= 0; --i) {
nodes[i]->printValue();
}
}
};
// Time: O(n)
// Space: O(n)
class Solution2 {
public:
void printLinkedListInReverse(ImmutableListNode* head) {
vector<ImmutableListNode *> nodes;
while (head) {
nodes.emplace_back(head);
head = head->getNext();
}
for (int i = nodes.size() - 1; i >= 0; --i) {
nodes[i]->printValue();
}
}
};
// Time: O(n^2)
// Space: O(1)
class Solution3 {
public:
void printLinkedListInReverse(ImmutableListNode* head) {
for (ImmutableListNode *tail = nullptr, *curr = nullptr; tail != head; tail = curr) {
for (curr = head; curr->getNext() != tail; curr = curr->getNext());
curr->printValue();
}
}
};