Remove (T &item) 应该删除 headPtr 并将该"item 值"存储在 "item" 中并返回 true,否则如果队列中没有元素,则返回 false。 我在此函数中收到"读取访问冲突错误"。以下是类和函数定义:
class SharedQueue {
public:
SharedQueue();
~SharedQueue();
//Return true if the queue is empty
bool IsEmpty() const;
//Enqueue the next item at the tail of the queue.
void Add(T value);
//Dequeue the next queue element and store it in "item" variable. The function returns false if the queue is empty and no item can be retrieved.
bool Remove(T &item);
void Print();
private:
struct QueueItem {
T item;
QueueItem *next;
};
//Fill in the The private data members.
QueueItem *headPtr;
QueueItem *tailPtr;
};
template <typename T> SharedQueue<T>::SharedQueue() {
headPtr = NULL;
tailPtr = NULL;
}
template <typename T>SharedQueue<T>::~SharedQueue() {
QueueItem *temp;
while (headPtr != NULL) {
temp = headPtr;
headPtr = headPtr->next;
delete temp;
}
}
template <typename T> bool SharedQueue<T>::IsEmpty() const {
if (headPtr == NULL && tailPtr == NULL) {
return true;
}
return false;
}
template <typename T> void SharedQueue<T>::Add(T aValue) {
if (headPtr == NULL) {
QueueItem *newItem = new QueueItem;
newItem->item = aValue;
tailPtr = headPtr = newItem;
}
else {
QueueItem *newItem = new QueueItem;
newItem->item = aValue;
tailPtr->next = newItem;
tailPtr = tailPtr->next;
}
}
template <typename T> bool SharedQueue<T>::Remove(T &item) {
if (headPtr == NULL) {
return false;
}
else {
QueueItem temp = *headPtr;
item = headPtr->item;
delete headPtr;
headPtr = temp.next;
return true;
}
}
template <typename T> void SharedQueue<T>::Print() {
QueueItem *temp = headPtr;
while (temp != NULL) {
std::cout << temp->item << "n";
temp = temp->next;
}
}
将项目添加到非空SharedQueue<T>
时:
QueueItem *newItem = new QueueItem;
newItem->item = aValue;
tailPtr->next = newItem;
tailPtr = tailPtr->next;
您从未设置newItem->next = NULL
。
您的私有struct QueueItem
可以(并且可能应该)拥有自己的构造函数/析构函数,以帮助确保一致地设置此类内容。