Rony Cohen Rony Cohen - 1 month ago 13
C++ Question

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 !

Answer

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)