Queue::addItem() is linking the new item on the end ok, but isn't updating pTail to point at the new end. Can someone help with this?
1 2 3 4 5 6 7 8 9 10 11
void Queue::addItem(char *pData)
{
QueueItem *pItem = new QueueItem(pData, ++_itemCounter);
if (0 == _pHead) // check for empty queue
_pHead = _pTail = pItem;
else
{
_pTail->setNext(pItem); // set current last item to point to new last item.
}
}
#pragma once
#include "QueueItem.h"
class Queue {
public:
Queue(); // ctor inits a new empty Queue
~Queue(); // dtor erases any remaining QueueItems
void addItem(char *pData);
void removeItem();
void Queue::deleteItem();
void print();
void erase();
private:
QueueItem *_pHead; // always points to first QueueItem in the list
QueueItem *_pTail; // always points to the last QueueItem in the list
int _itemCounter; // always increasing for a unique id to assign to each new QueueItem
};
Queue.cpp:
#include "Queue.h"
#include "QueueItem.h"
#include <iostream>
usingnamespace std;
void Queue::addItem(char *pData)
{
QueueItem *pItem = new QueueItem(pData, ++_itemCounter);
if (0 == _pHead) // check for empty queue
_pHead = _pTail = pItem;
else
{
_pTail->setNext(pItem); // set current last item to point to new last item.
}
}
void Queue::removeItem()
{
if(_pHead == 0)
{
cout << "Node cannot be deleted from empty list" << endl;
}
else
{
QueueItem* curr = _pHead;
_pHead = curr->getNext();
delete curr;
}
}
void Queue::print()
{
QueueItem* temp = _pHead;
while( temp != NULL)
{
cout << temp->getData() << endl;
temp-> getNext();
}
}
void Queue::erase()
{
while(_pHead != 0)
removeItem();
}
Queue::Queue(void)
{
_pHead = NULL;
_pTail = NULL;
}
Queue::~Queue(void)
{
erase();
}
QueueItem.h:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
#pragma once
class QueueItem {
public:
QueueItem(char *pData, int id); // ctor
void setNext(QueueItem *pItem);
QueueItem* getNext() const;
int getId() const;
constchar* getData() const;
private:
char _data[30]; // data value (null terminated character string)
constint _itemId; // unique id for item in queue
QueueItem* _pNext; // next item in queue
};