使用链表实现错误队列
Error Queue implementation using Linked List
我正在尝试使用链表实现队列,但它意外停止。
找不到原因?
#include <iostream>
#include <string>
using namespace std;
Class 节点创建节点。
class Node
{
public:
int data;
Node *next;
};
队列 Class 包含队列的操作。
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;
}
};
这里是主要函数
int main(){
Queue a;
a.enQueue(45);
a.dequeue();
a.dequeue();
}
第一次将一个节点加入队列时,您将取消引用一个空指针
void enQueue(int x){
Node* temp = NULL;
temp->data = x; // Wrong
取消引用空指针会产生 undefined behavior。
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;
}
您分配的地址无效。
这只会停止来自 "stopping unexpectidly" 的程序。不过还是有bug。
您的入队函数有错误。进行以下更改:
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;
}
现在您的程序将按预期运行
我正在尝试使用链表实现队列,但它意外停止。 找不到原因?
#include <iostream>
#include <string>
using namespace std;
Class 节点创建节点。
class Node
{
public:
int data;
Node *next;
};
队列 Class 包含队列的操作。
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;
}
};
这里是主要函数
int main(){
Queue a;
a.enQueue(45);
a.dequeue();
a.dequeue();
}
第一次将一个节点加入队列时,您将取消引用一个空指针
void enQueue(int x){
Node* temp = NULL;
temp->data = x; // Wrong
取消引用空指针会产生 undefined behavior。
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;
}
您分配的地址无效。
这只会停止来自 "stopping unexpectidly" 的程序。不过还是有bug。
您的入队函数有错误。进行以下更改:
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;
}
现在您的程序将按预期运行