使用推送时队列程序出现分段错误
Segmentation fault in queue program when using push
当我试图将元素推入队列时,我遇到了分段错误,我不是处理队列的专家,所以我不知道问题出在哪里。我一直在寻找这个问题的解决方案,即使人们遇到类似的问题,我也没有帮我解决问题。这是代码:
(我在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或破坏你程序的其他部分。
相关文章:
- 在某些循环内使用vector.push_back时出现分段错误
- 为什么在运行时没有向我们提供有关分段错误的更多信息?
- 如何解决gcc编译器优化导致的centos双编译器设置中的分段错误
- 当我的阵列太大时出现分段错误
- 分段错误当我试图运行程序时出错
- 在c++中初始化矩阵时出现分段错误(核心转储)
- 尝试使用集合函数时出现分段错误
- 我无法缩小此分段错误的原因
- g++的分段错误(在NaN上使用to_string两次时)
- 我是如何在这段代码中出现分段错误的
- 创建结构的数组时遇到分段错误
- 在c++中键入向量中的所有值后,得到分段错误(核心转储)
- 在 c++ 中实现 Trie 时出现分段错误
- 为什么 fstream 在打开带有格式的文件时会导致分段错误?
- 为什么我遇到分段错误?
- 动态类的分段错误(家庭作业问题)
- 分段错误 - 读取初始化指针的数组
- 如何摆脱C ++中的分段错误错误?
- 使用 CTYPE 时出现分段错误
- 为什么代码给出分段错误?