[英]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;
}
您必須知道,當您將新節點添加到您構建的列表時,您需要為新節點分配動態位置,然后將其添加到列表-queue-;
第二件事:當后面指向鏈接中的某個節點時,你需要讓新節點指向后面指向的節點,然后使后指針指向新節點。
新功能(pushBack)bacomes:
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
var。 它是一個指針,但它指向隨機數據,直到你告訴要指出什么。 當你按照指針時,它可以去任何地方並獲得段錯誤或打破程序的其他部分。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.