RameshRaju
RameshRaju

Reputation: 23

Self-Contained Linked List

My output:

The next node is: This

Here I get next node as This... The actual next node should be World. If I change my return value of Next() as,

return nextnode;

Then it prints,

The next node is: Hello

I am not able to print World as next node.

I need help doing this... Here is my code,

class Element
{
public:
    Element(const std::string& str):   data(str), next(nullptr)
    {

    }

    void Append(const Element& elem)
    {
        Element *tail = this;
        //printf("%s\n", tail->data.c_str());
        while (tail->next)
            tail = tail->next;
        tail->next = new Element(elem.data);
    }

    void Print(int n)
    {       
        if(n==1)
        {           
            printf("The next node is: %s\n", Next()->data.c_str());         
        }
    }   

    Element *Next()
    {
        Element *nextnode = this;
        if(nextnode->next)
            return nextnode->next;

        return NULL;
    }

private:    
    string data;
    Element *next;  
};

void main()
{
    // construct a list
    Element *root = new Element("Hello");

    root->Append(Element("World"));
    root->Append(Element("This"));
    root->Append(Element("Is"));
    root->Append(Element("a"));
    root->Append(Element("Linked"));
    root->Append(Element("List"));      
    root->Next()->Print(1);//It prints 'World' if I change code here as root->Print(1);
                                // But I dont want to change here...
}

Upvotes: 1

Views: 76

Answers (2)

nikolas
nikolas

Reputation: 8975

Your design is kind of strange. It is a valid choice to only print the next node, but that usually involves the creation of a dummy root node, because the "Hello" in node root is never accessable. That is also what is causing this strange behavior:

auto n = root->Next(); // Now we are at World
n->Print(1); // We print World->Next, so This

You could change your Print routine to not use the next, but the current node.

Upvotes: 2

spiritwolfform
spiritwolfform

Reputation: 2293

Your code is expected to print "This"
Because you call

root->Next()->Print(1);

And print is defined to print Next()->data.c_str(), by the way it's unsafe because Next() may be NULL.

So your list is like "Hello" -> "World" -> "This" where root is "Hello", root->Next is "World", and of course it will print "This" in your case

What you prabaly meant is to have the Print() method to print the current value, not the next node's value. So change it to

printf("The next node is: %s\n", data.c_str());  

And use standard streams for printing (std::cout) since it's c++

Upvotes: 3

Related Questions