1

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.

5 Answers 5

6

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.

Sign up to request clarification or add additional context in comments.

Comments

3

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.

Comments

1

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.

Comments

0
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.

2 Comments

I had to use node * nw = (node*) operator new (sizeof(node)); new (nw) node(d);
@Nitin thats pretty weird. What compiler do you use?
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.