|
| 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