My Queue数据结构实现出错

时间:2015-12-19 23:17:40

标签: c++ data-structures queue

我正在尝试使用链接列表实现队列,但是当我将整数传递给enqueue

中的main函数时,我收到此错误
  

抛出异常:写入访问冲突。

     

this-> tail is nullptr。

这是我的Queue.h

 #include <iostream>
using namespace std;

template <class T >
class Node
{
public:
    T data;
    Node* next;
    Node();
    Node(T _data);
};

template <class T>
class Queue
{

public:
    Node<T> *head, *tail;
    int elemsCnt;
    Queue();
    ~Queue();
    int count();
    void clear();
    void enqueue(T);
    T dequeue();
    T front();
    T back();
    bool empty();
};

这是我写的函数我的Queue.cpp ..     #include“Queue.h”

template <class T>
Node<T>::Node()
{
    next = NULL;
}

template <class T>
Node<T>::Node(T _data)
{
    data = _data;
    next = NULL;
}

template <class T>
Queue<T>::Queue()
{
    head = tail = NULL;
    elemsCnt = 0;
}

template <class T>
Queue<T>::~Queue()
{
    clear();
}

template <class T>
int Queue<T>::count()
{
    return elemsCnt;
}

template <class T>
bool Queue<T>::empty()
{
    return(elemsCnt == 0);
}

template <class T>
void Queue<T>::enqueue(T val)
{
    Node<T>* inserted = new Node<T>(val);
    tail->next = inserted;
    tail = inserted;
    ++elemsCnt;
}

template <class T>
T Queue<T>::dequeue()
{
    Node<T>* deleted = head;
    T val = head->data;
    head = head->next;
    delete deleted;
    --elemsCnt;

    if (empty())
        tail = NULL;

    return val;
}

template <class T>
T Queue<T>::front()
{
    return head->data;
}

template <class T>
T Queue<T>::back()
{
    return tail->data;
}

template <class T>
void Queue<T>::clear()
{
    while (!empty())
    {
        Node<T>* deleted = head;
        head = head->next;
        delete deleted;
        --elemsCnt;
    }
    tail = NULL;
}

2 个答案:

答案 0 :(得分:0)

因为最初你的队列是空的。当你有:

void Queue<T>::enqueue(T val)
{
    Node<T>* inserted = new Node<T>(val);
    tail->next = inserted; //at this point tail is still NULL
    //it is illegal to try to access * and . on NULL

    tail = inserted;
    ++elemsCnt;
}

如果你想修复它,试试这个:

void Queue<T>::enqueue(T val)
{
    Node<T>* inserted = new Node<T>(val);

    if(this->elemsCnt==0)
    {
        //empty Queue
        this->head=inserted;
        this->tail=inserted;
    }
    else
    {
        //non empty
        inserted->next=this->head; //make sure the new head can point to older head
        this->head=inserted; update the pointer for head.

    }
    ++elemsCnt;
}

答案 1 :(得分:0)

就像异常所说的那样,tail是NULL。当列表为空(head == tail == null)时,你的enqueue方法不处理这种情况。

template <class T>
void Queue<T>::enqueue(T val)
{
    Node<T>* inserted = new Node<T>(val);
    if (head == NULL)
    {
        head = tail = inserted;
    }
    else
    {
        tail->next = inserted;
        tail = inserted;
    }
    ++elemsCnt;
}