【发布时间】:2020-07-24 06:07:25
【问题描述】:
我正在尝试使用类编写一个链表,我希望它具有特定的格式。
例如,如果我有三个名为 p1、p2 和 p3 的数据和一个名为 list 的链表;我想把它们整理好。
list.insert(p1).insert(p2).insert(p3);
我试图返回对象,但没有成功。 这是我的代码。
#include<iostream>
using namespace std;
class linked_list {
public:
int *head;
linked_list();
~linked_list();
linked_list insert(int data);
};
linked_list::linked_list()
{
head = NULL;
}
linked_list::~linked_list()
{
int *temp;
int *de;
for (temp = head;temp != NULL;) {
de = temp->next;
delete temp;
temp = de;
}
delete temp;
//delete de;
}
linked_list linked_list::insert(int data)
{
int *temp;
temp = new int;
*temp = data;
temp->next = NULL;
if (head == NULL) {
head = temp;
}
else {
int* node = head;
while (node->next != NULL) {
node = node->next;
}
node->next = temp;
// delete node;
}
//delete temp;
return *this;
}
int main(){
linked_list l1;
int p1,p2,p3;
l1.insert(p1).insert(p2).insert(p3);
return 0;}
【问题讨论】:
-
显示的代码存在多个基本错误。不符合规则 3。引用的不当使用(没有任何使用)。您真正需要的是花更多时间with a good C++ textbook 并学习此处必须使用的基本 C++ 概念。这超出了在 stackoverflow.com 上快速回答的范围。
-
要允许正确的
list.insert(p1).insert(p2).insert(p3);,您必须返回参考。 -
int* node = head; while (node->next != NULL) {。哎哟... -
int*上的next应该从哪里来?您需要创建一个类来表示节点。
标签: c++ class pointers linked-list this