使用链接列表实现错误队列

时间:2015-06-06 07:38:27

标签: c++ data-structures linked-list queue

我正在尝试使用链接列表来表达队列,但它会无意中停止。 找不到原因?

#include <iostream>
#include <string>

using namespace std;

用于创建节点的类节点。

class Node
    {
    public:
        int data;
        Node *next;
    };

包含队列操作的队列类。

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();
}

3 个答案:

答案 0 :(得分:1)

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;
}

您正在分配无效地址。

这只会使程序停止&#34;意外停止&#34;。但仍然存在缺陷。

答案 1 :(得分:0)

第一次排队节点时,您将取消引用空指针

void enQueue(int x){
    Node* temp = NULL;
    temp->data = x; // Wrong

取消引用空指针会产生undefined behavior

答案 2 :(得分:0)

您的排队功能有误。进行以下更改:

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;
    }

现在您的程序将按预期运行

相关问题