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...
}
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++
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments