c++ - 自包含链表

标签 c++ linked-list

我的输出:

下一个节点是:这个

这里我将下一个节点作为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/

相关文章:

algorithm - 排序单循环链表

c++ - 链表实现链表

java - 单链表中节点的删除

c++ - 使用 AVX vector 警告编译旧版 GCC 代码

c++ - 比较一个字符串的两半

c++ - Win32C++编辑框下一行问题

java - 如果使用 LinkedList add 方法修改底层列表,iterator.next 是否也会被修改?

c++ - 使用 -mfma 编译时出现非法指令

c++ - 适当破坏某些类(class)成员

c - 删除双向链表中的第 n 个节点