gpt4 book ai didi

c++ - 自包含链表

转载 作者:行者123 更新时间:2023-11-30 01:21:02 25 4
gpt4 key购买 nike

我的输出:

下一个节点是:这个

这里我将下一个节点作为This...实际的下一个节点应该是World。如果我将 Next() 的返回值更改为,

return nextnode;

然后打印,

The next node is: Hello

我无法将 World 打印为下一个节点。

我需要帮助...这是我的代码,

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

最佳答案

你的代码应该打印“This”
因为你叫

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

并且 print 被定义为打印 Next()->data.c_str(),顺便说一下,它是不安全的,因为 Next() 可能为 NULL。

因此您的列表类似于“Hello”->“World”->“This”,其中 root 是“Hello”,root->Next 是“World” ,当然它会在你的情况下打印“This”

您的意思可能是让 Print() 方法打印当前值,而不是下一个节点的值。所以改成

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

并使用标准流进行打印 (std::cout) 因为它是 c++

关于c++ - 自包含链表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18609080/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com