프로그래밍2008.04.16 15:41

// Queue.h /////////////////////////////////////////////////////////////////
#ifndef	_Queue_h_
#define	_Queue_h_

class Queue
{
public:
	//
	// Constructors/Destructor
	//
	Queue();
	~Queue();

	//
	// Queue access
	//
	void push(void *obj);
	void *peek();
	void *pop();
	int Size() {return size;}

	//
	// Queue destruction
	//
	void destroy();

protected:
	//
	// These variables are to keep track of the linked list
	//
	void *head;
	void *tail;

	int size;
};

#endif
 
// Queue.cpp ///////////////////////////////////////////////////////////////
#include "Queue.h"

struct Queuenode
{
	Queuenode	*next;
	void		*obj;
};

//***************************************************************************
// Queue::Queue()
//
Queue::Queue()
{
	head = tail = 0;
	size = 0;
}

//***************************************************************************
// Queue::~Queue()
//
Queue::~Queue()
{
	destroy();
}

//***************************************************************************
// void Queue::destroy()
//
void Queue::destroy()
{
	while (head)
	{
		void	*obj = pop();
		delete obj;
	}
	size = 0;
	head = tail = 0;
}

//***************************************************************************
// void Queue::push(void *obj)
//    Push an object onto the Queue.
//
void Queue::push(void *obj)
{
	Queuenode	*node = new Queuenode;

	node->obj = obj;
	node->next = 0;
	if (tail)
		((Queuenode *) tail)->next = node;
	tail = node;
	if (!head)
		head = tail;
	size++;
}

//***************************************************************************
// void *Queue::pop()
//    Return the object at the head of the Queue and remove it
//
void *Queue::pop()
{
	if (size == 0)
		return 0;

	Queuenode	*node = (Queuenode *) head;
	void		*obj = node->obj;
	head = (void *) node->next;
	delete node;
	size--;

	if (!head)
		tail = 0;
	return obj;
}

//***************************************************************************
// void *Queue::peek()
//    Return the object at the top of the Queue.
//
void *Queue::peek()
{
	if (size == 0)
		return 0;

	return ((Queuenode *)head)->obj;
}
 
신고
Posted by jujubong

티스토리 툴바