C++STLキューコンテナの遍歴出力方法

2878 ワード

通常、独自のクラステンプレートを使用してチェーンキューを実装できます.
/**********************************      ********************************/
template
class LinkQueue;

template
class QNode {
protected:
	QElemType	data;
	QNode	*next;
public:
	friend class LinkQueue;
};

template
class LinkQueue {
protected:
	QNode	*front;
	QNode	*rear;
public:
	LinkQueue();
	virtual	~LinkQueue();
	Status	EnQueue(QElemType e);
	Status	DeQueue(QElemType &e);
	void	PrintQueue();
	int	QueueLength();
	Status	QueueEmpty();
};

template
LinkQueue::LinkQueue()
{
	front = rear = new(nothrow)QNode;
	if (!front)
		exit(LOVERFLOW);
	front->next = nullptr;
}

template
LinkQueue::~LinkQueue()
{
	while (front) {
		rear = front->next;
		delete front;
		front = rear;
	}
}

template
Status LinkQueue::EnQueue(QElemType e)
{
	QNode *p = new(nothrow)QNode;
	if (!p)
		return LOVERFLOW;
	p->data = e;
	p->next = nullptr;
	rear->next = p;
	rear = p;
	return OK;
}

template
Status LinkQueue::DeQueue(QElemType &e)
{
	QNode *p;
	if (front == rear)
		return ERROR;
	p = front->next;
	e = p->data;
	front->next = p->next;
	if (rear == p)
		rear = front;
	delete p;
	return OK;
}

template
void LinkQueue::PrintQueue()
{
	QNode *p = front->next;
	while (p) {
		cout << p->data << ' ';
		p = p->next;
	}
	cout << endl;
}

template
int LinkQueue::QueueLength()
{
	int i = 0;
	QNode *p = front->next;
	while (p) {
		i++;
		p = p->next;
	}
	return i;
}

template
Status LinkQueue::QueueEmpty()
{
	if (front == rear)
		return TRUE;
	return FALSE;
}

しかし,C++が持つSTLキューコンテナは,コードの先頭に加えてコード量に大きな利点がある.
#include 

次の機能を簡単に使用できます.
queue q;
q.empty();    //     ,  true
q.pop();    //         ,  !            
q.push(x);    // x       
q.front();    //      
q.back();    //      
q.size();    //         

キューコンテナはqの直接操作を許さないため、キューの遍歴出力はどのように行うべきか.私は昨日データ構造ハッシュテーブルを完成する過程で、このような問題に遭遇しました.その後、front操作を先に行い、最初の要素popを判断し、キューがemptyであるかどうかを判断すれば、このような機能を実現できることに気づきました.具体的な実現方式は以下の通りである.
while (!q.empty()) {
		cout << q.front() << " ";
		q.pop();
	}