2015-12-19 2 views
1

Я пытаюсь реализовать очереди с использованием связанного списка, но я получаю эту ошибку, когда я прохожу целое к функции enqueue в mainОшибки в моей очереди datastructres реализации

Исключения брошено: написать нарушение прав доступа ,

этот-> tail был 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; 
} 

ответ

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

хорошо, как исправить это ?? – zod101

+0

для очереди вам не нужен хвост, поэтому не беспокойтесь об этом слишком много. Если ваша очередь пуста, хвост имеет значение NULL, иначе это последний элемент. не полезно для очереди. – ForeverStudent

0

так же, как говорит исключение, хвост NULL. Метод enqueue не обрабатывает случай, когда список пуст (head == tail == null).

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

Я пробовал это и все равно даю мне ту же ошибку – zod101

+0

должен был бы увидеть последовательность enqueues/dequeues, так как логика выглядит правильно для меня. Я только что заметил, что в dequeue и clear, вы не устанавливаете head как null, так и хвост, когда последний элемент удален. Таким образом, я мог видеть это исключение, если вы в очереди, dequeue, а затем снова в очереди. – DBug

Смежные вопросы