Rony Cohen
Rony Cohen

Reputation: 97

Linked list overwrites the previous value

I want to create a linked list with classes. I have two classes, one LinkedList and another LinkedNode. My problem is that my function InsertAtEnd always delete the current node. So when I want to print my linked list, I can't see anything. I know thanks to debugger that in the function InsertAtEnd, we don't enter in the while loop, this is the problem. But after several attemps I can't resolve my problem.

This is my code:

void LinkedList::InsertAtend(int data)
{
    LinkedNode* node = new LinkedNode();
    node->setData(data); node->setNext(nullptr);

    LinkedNode* tmp = _header;
    if (tmp != NULL)
    {   
        while (tmp->getNext() != nullptr)
        {
            tmp = tmp->getNext();
        }
        tmp->setData(data);
        tmp->setNext(nullptr);
    }
    else
    {
        _header = node;
    }
}

My class LinkedNode:

class LinkedNode
{
public:
    LinkedNode();
    ~LinkedNode();
    void setData(int data);
    void setNext(LinkedNode* next);

    int getData() const;
    LinkedNode* getNext() const;

private:
    int _data;
    LinkedNode* _next;
};

My class LinkedList: #pragma once #include #include "LinkedNode.h" using namespace std;

class LinkedList
{
public:
    LinkedList();
    ~LinkedList();
    void PrintList();
    void InsertAtend(int data);
    void PrintList() const;

private:
    LinkedNode* _header;
};

Thanks for your help !

Upvotes: 0

Views: 251

Answers (3)

EmDroid
EmDroid

Reputation: 6046

At the end of the loop, the tmp is the last node in the current list. As you want to add the new node after the last node, you need to

tmp->setNext(node);

to append it (and not set the data as the data are already set to the new node).

Also note that you actually do not need to iterate through the entire list at all, if you keep another member variable to the current end of the list (_tail). Then you can access it directly and simply append and update.

Upvotes: 0

Pavel
Pavel

Reputation: 5866

tmp is the last Node, so if you don't want to delete it you shouldn't write value data in it. You should link it with the new Node, which you named node.

Instead of

tmp->setData(data);
tmp->setNext(nullptr);

You should write

tmp->setNext(node)

Upvotes: 1

UKMonkey
UKMonkey

Reputation: 6993

tmp->setData(data); Your tmp is not the node that you're trying to add, but the last in your list.

Upvotes: 2

Related Questions