链式队列的类模板与泛型编程

#ifndef 链式队列_H_
#define 链式队列_H_

template<class Object>
class Queue
{
public:
	Queue();
	~Queue();

	bool isEmpty() const;
	const Object & getFront() const;
	void enqueue(const Object & x); // enqueue 是入列,是针对于队列的是先入先出,类似于push对用于栈,
	Object dequeue();               // dequeue 是出列,
	void makeEmpty();
private:
	struct ListNode
	{
		Object element;
		ListNode *next;

		ListNode(const Object & theElement, ListNode *n = 0)
			: element(theElement), next(n) {}
	};
	ListNode *front;
    ListNode *back;
};

template<class Object>
Queue<Object>::Queue()
{
	front = back = 0;
}

template<class Object>
Queue<Object>::~Queue()
{
	makeEmpty();
}

template<class Object>
void Queue<Object>::makeEmpty()
{
	while(!isEmpty())
		dequeue();
}

template<class Object>
bool Queue<Object>::isEmpty() const
{
	return front == 0;
}

template<class Object>
const Object & Queue<Object>::getFront() const
{
	if(isEmpty())
		throw "Queue is empty,";
	return front->element;
}

template<class Object>
void Queue<Object>::enqueue(const Object &x)
{
	if(isEmpty())
		back = front = new ListNode(x);
	else
		back = back->next = new ListNode(x);
}

template<class Object>
Object Queue<Object>::dequeue()
{
	Object frontItem = getFront();

	ListNode *old = front;
	front = front->next;
	delete old;

	return frontItem;
}


#endif
#include <iostream>
#include "链式队列.h"

using namespace std;

int main()
{
	cout << "xiao cui" << endl;
	Queue<int> myQ;

	myQ.enqueue(2);
	myQ.enqueue(4);
	myQ.enqueue(8);

	cout << myQ.getFront() << endl;
	myQ.dequeue();
	cout << myQ.getFront() << endl;
	cout << myQ.dequeue() << endl;

	for(int j = 0; j < 8; j++)
	{
		for(int i = 0; i < 8; i++)
			myQ.enqueue(i);
		while(!myQ.isEmpty())
			cout << myQ.dequeue() << endl;
	}

	return 0;
}


你可能感兴趣的:(链式队列的类模板与泛型编程)