使用推送时队列程序出现分段错误

Segmentation fault in queue program when using push

本文关键字:分段 错误 程序 队列      更新时间:2023-10-16

当我试图将元素推入队列时,我遇到了分段错误,我不是处理队列的专家,所以我不知道问题出在哪里。我一直在寻找这个问题的解决方案,即使人们遇到类似的问题,我也没有帮我解决问题。这是代码:

(我在Dev-c++5.9.2中使用了调试选项,它告诉我"temp->link=NULL;"这一行导致了问题,但我不知道如何解决它)

#include <iostream>
using namespace std;
struct Node {
    int data;
    Node* link;
};
class Queue {
public:
    Queue(); 
    ~Queue(); 
    void pushBack(int d);
    bool popFront(); 
    bool isEmpty(); 
    void displayQueue();
private:
    Node* back;
    Node* front;
};
Queue::Queue() {
    back = NULL;
    front = NULL;
}
Queue::~Queue() {
        while (!isEmpty()) {
        popFront();
    }
}
void Queue::pushBack(int d) {
    Node* temp;
    if (temp == NULL) {
    return;
    } else {
            temp->link = NULL; <========== This is where is get the error
            if (back == NULL) {
                  back = temp;
                  front = temp;
            } else {
                  front->link = temp; <===== here too
              front = temp;
            }
      }
}

bool Queue::popFront() {
    if (front == NULL) {
        return false;
    } else {
        Node* removeNode;
        removeNode = front;
        if (back == front) {
            back = NULL;
            front = NULL;
        } else {
            Node* previousFront = back;
            while (previousFront->link != front) {
                previousFront = previousFront->link;
            }
            front = previousFront;
            front->link = NULL;
        }
        delete removeNode;
        return true;
    }
}
bool Queue::isEmpty() {
    return (back == NULL);    
}
void Queue::displayQueue() {
    if (isEmpty()) {
        cout << "Queue is empty!" << endl;
    } else {
        Node *current;
        current = back;
        cout << endl << "-- BACK --  ";
        while (current != NULL) {
        cout << current->data << "  ";
        current = current->link;
        }
        cout << "-- FRONT --" << endl << endl;
    }
}
int main(){
    Queue q;
    q.displayQueue();
    q.pushBack(20);
    q.pushBack(30);
    q.displayQueue();
    q.pushBack(40);
    q.pushBack(12);
    q.displayQueue();
    q.popFront();
    q.displayQueue();
    return 0;
}

当您添加新节点到您构建的列表,您需要分配一个动态新节点的位置,然后将其添加到列表-队列-;

第二件事:当背面已经指向链接中的某个节点时您需要使新节点指向背面所指向的节点,然后使返回指针指向新节点。

新功能(pushBack)回归:

void Queue::pushBack ( int d ) {
Node* temp = new Node;
temp->data = d;
temp->link = NULL;
        if (back == NULL) {
            back = temp;
            front = temp;
        }
        else {
            temp->link = back;
            back = temp;
        }

}

您正在创建一个指向节点的指针,但尚未创建该节点。(其他人都说了什么)

更改

Node* temp;-堆栈存储器

Node *temp = new Node()-堆内存

我不是处理队列的专家,所以我不知道的问题在哪里

请注意,问题与队列无关:问题在于理解语言是如何工作的。

正如Thornkey所指出的,在您的pushBack函数中有一个temp变量。它是一个指针,但它指向随机数据,直到你知道该指向什么。当你跟随指针时,它可能会去任何地方,得到一个segfault或破坏你程序的其他部分。