我为我的作业创建了一个处理链接列表的程序。在我输入一个数字之前它运行正常然后它崩溃了我给我一个分段错误错误。 我知道这意味着什么,但我找不到问题。
看一看,看看你是否可以帮助我!谢谢!
#include <iostream>
using namespace std;
struct node //node structure
{
int number;
node *next;
};
bool isempty(node *head);
char menu();
void first(node *&head, node *&last, int number );
void insert(node *&head, node *&last, int number);
void remove(node *&head, node *&last);
void shownode(node *current);
bool isempty(node *head)
{
if(head = NULL)
return true;
else
return false;
}
char menu()
{
char choice;
cout<<"choose and option:"<<endl;
cout<<"1. Add Node."<<endl;
cout<<"2. Remove Node."<<endl;
cout<<"3. Show Node List."<<endl;
cout<<"4. Exit Program."<<endl;
cin>>choice;
return choice;
}
void first(node *&head, node *&last, int number ) //adding first
{
node *temp =new node;
temp->number = number;
temp->next = NULL;
head = temp;
last = temp;
}
void insert(node *&head, node *&last, int number)//adding more
{
if(isempty(head))
first(head, last, number);
else
{
node *temp =new node;
temp->number = number;
temp->next = NULL;
last->next = temp;
last = temp;
}
}
void remove(node *&head, node *&last)//destructor
{
if(isempty(head))
cout<<"List is empty."<<endl;
else if (head == last)
{
delete head;
head == NULL;
last == NULL;
}
else
{
node *temp = head;
head = head->next;
delete temp;
}
}
void shownode(node *current)
{
if (isempty(current))
cout<<"list is empty"<<endl;
else
{
cout<<"Nodes in list:"<<endl;
while(current != NULL)
{
cout<<current->number<<endl;
current = current->next;
}
}
}
int main()
{
node *head = NULL;
node *last = NULL;
char choice;
int number;
do{
choice = menu();
switch(choice)
{
case '1': cout<<"inert number:"<<endl;
cin>>number;
insert(head, last, number);
break;
case '2': remove(head, last);
break;
case '3': shownode(head);
break;
default: cout<<"Exit";
}
}while(choice != '4');
return 0;
}
这是我得到的错误:
选择和选项: 1.添加节点。 2.删除节点。 3.显示节点列表。 4.退出计划。 1 惰性数: 44
跑完了;分段故障:11;实时:2s;用户:0ms; system:0ms
答案 0 :(得分:2)
首先,这行代码,
if(head = NULL)
应该是,
if(head == NULL)
答案 1 :(得分:0)
不知道你是否误解'='和'==','='表示赋值,'=='判断是否相等。
在bool isempty(node *head)
函数中
if(head = NULL)
=&gt; if (head == NULL)
在remove(node *&head, node *&last)
函数
else if (head == last)
{
delete head;
head == NULL;
last == NULL;
}
应该是
else if (head == last)
{
delete head;
head = NULL;
last = NULL;
}