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开发者_JAVA百科 = 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 to nw
. However, since nw
is a local variable, it will cease to exist when the function returns. So the next
pointer of the last node now points to something that no longer exists. You need to use new node(d)
(which returns a pointer to a node
) in order to create an object that will continue to exist after the function has returned.
You error is that you create an object on the stack, then store a pointer to it. The stack gets overwritten, your object gets overwritten, your pointer is invalid.
In your case the node that holds 3 is in the end overwritten by the node that holds 81.
Might I also suggest that you make a LinkedList class separate from the Node class? You can then move the append() method to that class and have it manage your nodes.
void node::append(int d) {
node *nw = new node(d);
node *last = this;
while((*last).next!=NULL)
last = (*last).next;
(*last).next = nw;
}
Yes, if your object are meant to stay around after function finishes you should create them on the heap (the new keyword), not on stack.
by using
node *nw=new node(d);
gives pointer to the same location every time which leads to the over-writing of the data. so even by using new , the output is 81
find a way to create a new node which points to different memory address
my comments are blocked so i wrote this is answer sorry for the inconvenience
精彩评论