mel-
mel-

Reputation: 533

Linked list leaks?

I am not too versed in C++, but I had the task of designing and implementing a linked list. This is what I handed in:

template <typename T>
struct Node
{
    Node() : next(nullptr) {}
    Node(T const & val) : next(nullptr), value(val) {}

    Node * next;
    T value;
};

template <typename T>
class LinkedList
{
    public:
        LinkedList()
        {
            begin_ = new Node<T>;
            current_ = begin_;
        }
        ~LinkedList()
        {
            delete begin_;
        }

        void insert(T const & value)
        {
            Node<T> * node = new Node<T>(value);
            node->next = current_->next;
            current_->next = node;
            current_ = current_->next;
        }

        void remove()
        {
            Node<T> * tmp = current_->next;
            if(!end())
            {
                current_->next = current_->next->next;
            }
            delete tmp;
        }

        bool end() const
        {
            return current_->next == nullptr;
        }

        void reset()
        {
            current_ = begin_;
        }

        void advance()
        {
            if(!end())
            {
                current_ = current_->next;
            }
        }

        T get() const
        {
            return current_->next->value;
        }

    private:
        Node<T> * begin_;
        Node<T> * current_;
};

I passed the assignment, but my teacher underlined the delete begin_ in the destructor ~LinkedList() and wrote "This leaks!" next to it. I have been thinking about how delete begin_ could possibly leak but I still do not understand. Can someone please help me with this?

Upvotes: 1

Views: 147

Answers (3)

Alexander
Alexander

Reputation: 23537

I think you will understand it better this way:

~LinkedList()
{
  reset();
  while(!end()) remove();
}

Upvotes: 0

Luke
Luke

Reputation: 560

In the destructor of Node it should send the delete command to next so that it frees up all nodes in the list.

Upvotes: 0

trumpetlicks
trumpetlicks

Reputation: 7065

You have to go through every node in the list and delete. Hold a separate pointer to next, delete current, then move forward and continue deleting until next pointer is null.

~LinkedList()
{
    Node * current = begin_;
    Node * aNext = begin_->next;

    while (null != aNext){
        delete(current);
        current = aNext;
        aNext = current->next;
    }
}

Something like this. Don't know where you're getting begin_ from, but........

Upvotes: 2

Related Questions