【发布时间】:2021-08-18 10:27:02
【问题描述】:
我刚开始学习 c++,我正在做一个任务,要求我们使用链表构建队列,但是当我尝试我的“显示函数”时,我得到了一个 Thread 1: EXC_BAD_ACCESS (code=EXC_I386_GPFLT) 错误,我这个函数背后的逻辑是那个小箭头(->) 是解引用指针,所以理论上应该可以打印出节点内部的数据。谁能告诉我我的代码有什么问题?
#include <iostream>
using namespace std;
struct node{
int data;
node *next;
};
node *front, *last, *use;
bool isempty(){
if(front == NULL)
return false;
else
return true;
}
void add(int a){
node *t = new node;
t->data = a;
if(isempty()==false){
front = t;
last = t;
}else{
front = front->next;
t->next = front;
front = t;
}
}
void goaway(){
if(isempty()==true){
use = front;
do{
last = use;
use = use->next;
}while(use->next!=NULL);
if(use->next == NULL)
cout<<"You just delete: "<<use->data<<endl;
delete use;
}
else{
cout<<"Nothing in here. "<<endl;
}
}
void display(){
cout<<"Your stored element: "<<endl;
for (use = front; use!=NULL; use = use->next) {
cout<<use->data;
}
cout<<"\n";
}
int main(){
front= NULL;
last = NULL;
int flag = 1;
while(flag == 1){
int choice;
cout<<"1 add 2 remove 3 display 4 exit"<<endl;
cin>>choice;
switch (choice) {
case 1:
int a;
cout<<"Input element!"<<endl;
cin>>a;
add(a);
break;
case 2:
goaway();
break;
case 3:
display();
break;
case 4:
flag = 2;
default:
cout<<"wrong choice!!"<<endl;
flag = 3;
break;
}
}
}
【问题讨论】:
-
为了“使用链表构建队列”,您应该使用en.cppreference.com/w/cpp/container/list 并以效率给您的老师留下深刻印象。
-
我对@987654324@ 的实现感到困惑。它具有反转逻辑。一个 NULL 前指针让你“它不是空的”作为答案。幸运或不幸的是,您也相应地滥用了它......
-
在
t->data = a;之后你无法初始化t->next = NULL;(或nullptr——你的选择)然后当你迭代时,例如while(use->next!=NULL)末尾的->next指针不是NULL,因此当您继续尝试读取列表末尾的内容时调用未定义行为导致EXC_BAD_ACCESS。 -
写一个合适的
queue类,而不是一堆全局变量。现在您正在尝试在列表的前面添加元素并从尾部检索元素(循环),考虑将last指针存储到列表的尾部并将元素添加到所述尾部,同时从前面删除元素. -
@Yunnosch,谢谢!我会调查一下,你是对的,哈哈哈它是倒置的,我应该改变它。