Trying to build a queue using linked list in c++ but got this error:

Trying to build a queue using linked list in c++ but got this error:

我刚开始学习 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;
        }
    }
}

首先,在 add 函数的 else block 中,我不明白你为什么在添加新节点时递增 front。通过执行 front = front->next 你的前指针总是指向列表中的第二个节点,每当你调用 add 函数时,你的第一个节点每次都会浪费,结果 no nodes in the list.

其次,在您的 add 函数中,在 t->data = a; 之后您没有初始化 t->next = NULL 这就是您面临未定义行为的原因。

你的添加函数应该是这样的:

void add(int a) {
    node* t = new node;
    t->data = a;
    t->next = NULL;
    if (isempty() == false) {
        front = t;
        last = t;
    }
    else {
        t->next = front;
        front = t;
    }
}