【发布时间】:2014-06-29 15:31:23
【问题描述】:
我已经开始学习 C++ 中的链表,并且我已经编写了一个程序来创建和显示一个列表。它编译得很好,但执行失败。
代码如下:
#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;
}
这是输出:
Creating list...
Enter the size of the list you want to create.
3
Enter the data for node number 1
1
因此,第二个节点的数据不被接受。我是链表的新手,想尝试以这种方式解决问题,但我在这方面花了太多时间。我哪里出错了?
【问题讨论】:
-
这是题外话,因为 SO 不是调试服务。
-
这是一个让您体验调试器的好机会。您使用的是什么 IDE?
-
因此,作为解决此问题的第一步,在调试器中启动您的程序,逐行执行,观察变量如何变化。这应该让您对实际发生的事情有一个很好的印象。
-
您应该了解什么是调试器以及如何使用它来查找代码中的错误。
标签: c++ list linked-list