使用单链表(C+;+;)计划提供帮助 我已经开始学习C++中的链表,我编写了一个程序来创建和显示列表。它编译得很好,但执行失败
代码如下:使用单链表(C+;+;)计划提供帮助 我已经开始学习C++中的链表,我编写了一个程序来创建和显示列表。它编译得很好,但执行失败,c++,list,linked-list,C++,List,Linked List,代码如下: #include <iostream> using namespace std; class node { public: int data; // information contained by the node node *next; // a pointer pointing to an instance of the class node. }; cl
#include <iostream>
using namespace std;
class node
{
public:
int data; // information contained by the node
node *next; // a pointer pointing to an instance of the class node.
};
class list
{
public:
node *head;
node *temp, *tp;
void createlist();
void displaylist();
};
void list :: createlist()
{
int size;
cout<<"Enter the size of the list you want to create.\n";
cin>>size;
temp=head;
for(int k=1;k<=size;k++)
{
if(head == NULL)
{
head = new node[1];
cout<<"Enter the data for node number 1\n";
cin>>head->data;
head->next=NULL;
}
else
{
temp->next=new node[1];
temp=temp->next;
cout<<"Enter the data for node number \n"<<k;
cin>>temp->data;
temp->next=NULL;
}
}
}
void list::displaylist()
{
if (head==NULL)
{
cout<<"List is empty.";
}
else
{
while(tp!=NULL)
{
tp = head;
cout<<tp->data;
tp = tp->next;
}
}
}
int main()
{
list obj;
cout<<"Creating list...\n";
obj.createlist();
cout<<"Displaying list...\n";
obj.displaylist();
return 0;
}
#include <iostream>
using namespace std;
class node
{
public:
int data; // information contained by the node
node *next; // a pointer pointing to an instance of the class node.
};
class list
{
public:
node *head;
node *temp, *tp;
void createlist();
void displaylist();
};
void list::createlist()
{
int size;
cout<<"Enter the size of the list you want to create.\n";
cin>>size;
temp=head;
for(int k=1;k<=size;k++)
{
if(head == NULL)
{
head = new node[1];
cout<<"Enter the data for node number 1\n";
cin>>head->data;
head->next=NULL;
}
else
{
temp->next=new node[1];
temp=temp->next;
cout<<"Enter the data for node number \n"<<k;
cin>>temp->data;
temp->next=NULL;
}
}
}
void list::displaylist()
{
if (head==NULL)
{
cout<<"List is empty.";
}
else
{
while(tp!=NULL)
{
tp = head;
cout<<tp->data;
tp = tp->next;
}
}
}
int main()
{
list obj;
cout<<"Creating list...\n";
obj.createlist();
cout<<"Displaying list...\n";
obj.displaylist();
return 0;
}
#包括
使用名称空间std;
类节点
{
公众:
int data;//节点包含的信息
node*next;//指向类节点实例的指针。
};
班级名单
{
公众:
节点*头;
节点*temp,*tp;
void createlist();
void displaylist();
};
void list::createlist()
{
整数大小;
coutsize;
温度=水头;
对于(int k=1;kdata;
head->next=NULL;
}
其他的
{
temp->next=新节点[1];
温度=温度->下一步;
coutnext=NULL;
}
}
}
无效列表::显示列表()
{
if(head==NULL)
{
cout数据成员head和tp在创建对象obj时未初始化,并且具有任意值。因此,程序具有未定义的行为。另外,将临时变量作为类的tp或temp数据成员也是一个坏主意。它们必须是使用它们的成员函数的局部变量
没有任何传感器可以像您这样分配节点数组
head = new node[1];
/...
temp->next=new node[1];
简写
head = new node();
/...
temp->next=new node();
另外,最好将类节点定义为类列表的内部类
不要忘了编写析构函数以释放分配的内存。这不是主题,因为这不是一项调试服务。这是一个很好的机会,让您可以使用调试器。您使用的是什么IDE?因此,作为解决此问题的第一步,在调试器中启动程序,逐行执行,然后观看h变量如何变化。这会给你一个很好的印象。你应该学习什么是调试器,以及如何使用调试器来查找代码中的错误。