C++ 自足链表
我用这个方法创建了一个链表C++ 自足链表,c++,linked-list,C++,Linked List,我用这个方法创建了一个链表 class stack { struct node { int data; node *link; }*top; void insert() { ... } void display() { ... } }; 而且效果很好。。。现在,我正试图对一个自包含的链表执行相同的操作,但最终出现了错误。这是我的密码 class Element { public: Element(const std::str
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"));
}
我只想修改我的元素类,但我不清楚
我可能在我的程序中犯了一些愚蠢的错误,因为我不熟悉数据结构,而且我对在线引用感到困惑。在构造函数中-
head = NULL;
head -> data = str;
代码具有未定义的行为。您不应该访问空指针上的成员。在head
指向正确的内存位置后,您还应该执行以下操作-
head -> next = NULL;
在构造函数中,追加操作才能可靠地工作。我认为Element::Append
应该接收std::string
参数,因为您正在尝试执行此操作-
newnode->data = elem;
我认为你的设计是错误的。我可能是在猜测你老师的意思,但我认为完整的列表应该是这样的
class Element
{
public:
Element(const std::string& str)
{
data = str;
next = NULL;
}
void Append(const Element& elem)
{
Element* tail = this;
while (tail->next)
tail = tail->next;
tail->next = new Element(elem.data);
}
private:
string data;
Element *next;
};
换句话说,元素
是节点类。我想这就是你们老师所说的“自包含链表类”和“元素不是管理类”的意思
在
main
代码中,您将看到列表的开头是如何位于变量root
中的。但是您也试图在Element::head
中保留列表的开头。因此,对于您的设计,列表的开头被放在两个地方,这没有多大意义。我不认为这是你老师想要的,但我可能错了。main
必须有int
的返回类型。很抱歉,我不能。。。如果Element是一个节点类,我应该如何响应,Element*root=newelement(“Hello”);和root->Append(元素(“世界”);对不起,我没有老师要问。我唯一的学习方式是在线学习,但我找不到这种类型的任何方法。我了解在void Append(const Element&elem)和void print(int)const中使用const,但是为什么我们使用const here元素(const std::string&str)而没有const here错误发生。。。为什么会这样?如果你能做printf(“%s\n”,tail->data.c_str()),我就不能正常打印它了然后你也可以做cout数据代码>。为什么cout在元素(const std::string&str)
中需要const的原因很复杂。恐怕太复杂了,不能用简短的评论来解释。但是,当您编写元素(“hello”)
时,您正在从string literal“hello”
创建一个临时std::string
对象,并且该临时对象不能绑定到非常量引用。我说这很复杂。