I am trying to implement a simple linked list using c++. I am probably making a silly mistake somewhere.Through this i want to learn classes and pointers in C++.
For the code
#include <iostream>
using namespace std;
class node
{
public:
node* next;
int data;
node(int d);
void append(int d);
};
node::node(int d)
{
data = d;
next = NULL;
}
void node::append(int d)
{
node nw = node(d);
if(next==NULL)
next = &nw;
else
{
node *n = next;
while((*n).next!=NULL)
{
n = (*n).next;
}
(*n).next = &nw;
}
}
I am getting 81 as the node next to 1.
int main()
{
node n = node(1);
n.append(3);
n.append(2);
n.append(81);
n = *(n.next);
cout<< n.data << '\n';
}
Please help me figure out where am i making mistake.
There might be other errors, but this is extremely dangerous: You are creating a local variable to represent the new node:
node nw = node(d);, and then you make the last node in the list point tonw. However, sincenwis a local variable, it will cease to exist when the function returns. So thenextpointer of the last node now points to something that no longer exists. You need to usenew node(d)(which returns a pointer to anode) in order to create an object that will continue to exist after the function has returned.