C++ 使用链表实现错误队列
我试图使用链表实现队列,但它意外地停止了。 找不到原因C++ 使用链表实现错误队列,c++,data-structures,linked-list,queue,C++,Data Structures,Linked List,Queue,我试图使用链表实现队列,但它意外地停止了。 找不到原因 #include <iostream> #include <string> using namespace std; 包含队列操作的队列类 class Queue{ private: Node* front = NULL; Node* rear = NULL; public: void enQueue(int x){ Node* temp = NULL; temp->
#include <iostream>
#include <string>
using namespace std;
包含队列操作的队列类
class Queue{
private:
Node* front = NULL;
Node* rear = NULL;
public:
void enQueue(int x){
Node* temp = NULL;
temp->data = x;
temp->next = NULL;
if(front == NULL && rear == NULL){
front = rear = NULL;
return;
}
rear->next = temp;
rear = temp;
}
void dequeue()
{
Node* temp = front;
if(front == NULL)
{
cout << "No list found." << endl;
return;
}
if(front == rear){
front = rear = NULL;
}
else{
front = front->next;
}
delete temp;
}
};
第一次将节点排入队列时,将取消对空指针的引用
void enQueue(int x){
Node* temp = NULL;
temp->data = x; // Wrong
取消对空指针的引用会产生错误
您正在分配给一个无效的地址
这只会阻止程序“意外停止”。但是仍然存在错误。您的排队函数中有一个错误。进行以下更改:
void enQueue(int x){
Node* temp = new Node();//you need to create this variable and not set it to NULL
temp->data = x;
temp->next = NULL;
if(front == NULL && rear == NULL){
front = rear = temp;
return;
}
rear->next = temp;
rear = temp;
}
现在,您的程序将按预期运行
void enQueue(int x){
Node* temp = NULL;
temp->data = x; // Wrong
void enQueue(int x){
Node* temp = NULL; //Node* temp = new Node;
temp->data = x; //BOOM
temp->next = NULL;
if(front == NULL && rear == NULL){
front = rear = NULL; //What?
return;
}
rear->next = temp;
rear = temp;
}
void enQueue(int x){
Node* temp = new Node();//you need to create this variable and not set it to NULL
temp->data = x;
temp->next = NULL;
if(front == NULL && rear == NULL){
front = rear = temp;
return;
}
rear->next = temp;
rear = temp;
}