这一个由双链表实现的内存中立的队列,进队的新节点next指针指向head节点,head节点的prev指针指向入队最后节点。与stl中的queue比较,由于不分节点内存,所以非常高效,使用时要求每一个存储的节点包含一个Entry的实例,要存储节点必须在堆中分配内存。
/**
*
* @class single thread queue(squeue)
* @brief A "memory neutral" queue.
*/
#include <portable.h>
class Queue
{
Queue(const Queue&);
Queue& operator = (const Queue&);
public:
class Entry;
INLINE Queue() {
clear();
}
INLINE void clear() {
head.next = &head;
head.prev = &head;
}
INLINE void push(Entry* n) {
n->prev = head.prev;
n->prev->next = n;
n->next = &head;
head.prev = n;
}
INLINE Entry* getHead() {
return (head.next == &head) ? NULL : head.next;
}
INLINE Entry* getTail() {
return (head.prev == &head) ? NULL : head.prev;
}
INLINE void remove(Entry* n) {
n->remove();
}
/// Is the list empty?
INLINE bool isEmpty (void) const {
return (head.getPrev() == &head);
}
/// An entry in the list.
class Entry {
public:
// private:
INLINE void setPrev (Entry * p) { assert (p != NULL); prev = p; }
INLINE void setNext (Entry * p) { assert (p != NULL); next = p; }
INLINE Entry * getPrev (void) const { return prev; }
INLINE Entry * getNext (void) const { return next; }
INLINE void remove (void) const {
prev->setNext(next);
next->setPrev(prev);
}
Entry * prev;
Entry * next;
};
private:
Entry head;
};