我用这个方法创建了一个链表...
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/