C++ c++;linkedlist中的分段错误
我为我的家庭作业创建了一个处理链表的程序。在我输入一个数字之前,它运行良好,然后它崩溃了,给了我一个分段错误。 我知道这意味着什么,但我找不到问题的答案 看看你能不能帮我一把!谢谢C++ c++;linkedlist中的分段错误,c++,C++,我为我的家庭作业创建了一个处理链表的程序。在我输入一个数字之前,它运行良好,然后它崩溃了,给了我一个分段错误。 我知道这意味着什么,但我找不到问题的答案 看看你能不能帮我一把!谢谢 #include <iostream> using namespace std; struct node //node structure { int number; node *next; }; bool isempty(node *head); char menu();
#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;
}
#包括
使用名称空间std;
结构节点//节点结构
{
整数;
节点*下一步;
};
布尔为空(节点*头部);
字符菜单();
首先无效(节点*&头部,节点*&最后,整数);
无效插入(节点*&头部、节点*&最后一个、整数);
无效删除(节点*&头部、节点*&最后);
void shownode(节点*当前);
bool isempty(节点*头)
{
if(head=NULL)
返回true;
其他的
返回false;
}
字符菜单()
{
字符选择;
cout首先,这行代码
if(head = NULL)
应该是,
if(head == NULL)
不知道您是否误解了“=”和“=”,“=”表示赋值,“=”判断是否相等。
在boolisempty(节点*头部)
函数中
if(head=NULL)
=>if(head=NULL)
在删除(节点*&头部,节点*&最后一个)
功能中
else if (head == last)
{
delete head;
head == NULL;
last == NULL;
}
应该是
else if (head == last)
{
delete head;
head = NULL;
last = NULL;
}
在调试器下运行程序。它会告诉你故障发生在哪一行。别让我们猜。好吧,我觉得很愚蠢。这很好地解决了它!有时你只需要第二双眼睛就能捕捉到错误。谢谢!