closed

thank you!!
Last edited on
Because you only have a singly-linked list, it is impossible to traverse it backwards in the normal sense. The 2 easiest ways I can think of would be to either make it a doubly-linked list or create a sortable container with pointers to the list, and then going in reverse order:
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
#include <deque>
#include <iostream>

// either doubly linked (you'll need to edit your NumberList to match)
template <typename T>
struct ListNode {
    T value;
    ListNode<T>* prev;
    ListNode<T>* next;
};

// or store all the nodes in a temporary
template <typename T>
class NumberList {
    public:
        // ...

        void reverse() {
            std::deque<ListNode<T>*> nodes;
            ListNode<T>* ptr = head;
            while (ptr) {
                nodes.push_front(ptr);
                ptr = ptr->next;
            }

            for (std::size_t i = 0; i < nodes.size(); ++i)
                std::cout << nodes[i]->value << " ";
            std::cout << std::endl;
        }
};
Last edited on
Topic archived. No new replies allowed.