c++ - 自包含链表

标签 c++ linked-list

我用这个方法创建了一个链表...

class stack
{
    struct node
    {
        int data;
        node *link;
    }*top;

void insert()
{ ... }

void display()
{ ... }

};

它工作正常...现在我试图用一个独立的链表做同样的操作,但我最终遇到了错误。这是我的代码

class Element
{
public:
    Element(const std::string& str)
    {
        head = NULL;
        head -> data = str;
    }
    void Append(const Element& elem)
    {
        node *newnode;
        newnode=new node;
        newnode->data = elem;
        node *target=head;

        while(target->next != NULL)
            target = target->next;

        target -> next = newnode;
    }

private:
    struct node
    {
        string data;
        node *next;
    }*head;
};

void main()
{   
    Element *root = new Element("Hello");

    root->Append(Element("World"));
}

我只想修改我的 Element 类,但我不清楚。

我可能在我的程序中犯了一些愚蠢的错误,因为我是数据结构的新手,而且我对在线引用感到困惑。

最佳答案

在构造函数中——

head = NULL;
head -> data = str;

代码有未定义的行为。您不应访问 NULL 指针上的成员。在 head 指向正确的内存位置之后,您还应该做 -

head -> next = NULL;

在追加操作的构造函数中可靠地工作。我认为 Element::Append 应该收到 std::string 参数,因为您正在尝试这样做 -

newnode->data = elem;

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

相关文章:

c++ - 用于制作 CCleaner 的库

c++ - 检查所有字符串(小说列表)中是否存在任何字母(a-z)并打印找到的字母数的程序

c - 这些c struct声明之间的区别?

c - 打印链表时出现段错误

c++ - 链表的数组实现

c++ - 错误 : unqualified ID

c++ - 为什么 Eclipse-CDT 说自赋值是错误的?

c++ visual studio 2008 链接问题

c - 从链表中删除字符串 - C

C++ 链表 : Problem with struct inside class