QueueLi.h头文件源代码:
#ifndef
_QUEUELI_H_
#define
_QUEUELI_H_
template
class
Queue
{
public:
Queue(); //构造函数
~Queue(); //析构函数
bool
IsEmpty()
const; //判断队列是否为空
const
Object& getFront()
const; //获取队首元素
void
enqueue(const Object&
x); //入队函数
Object
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
Queue
{
front
= back = NULL;
}
template
Queue
{
MakeEmpty();
}
template
void
Queue
{
while
(!IsEmpty())
dequeue();
}
template
bool
Queue
{
return
front == NULL;
}
template
const
Object& Queue
{
if
(IsEmpty())
throw
"Queue is empty";
return
front->element;
}
template
void
Queue
{
if
(IsEmpty())
back
= front = new ListNode(x);
else
{
back->Next
= new ListNode(x);
back
= back->Next;
}
}
template
Object
Queue
{
Object
frontItem = getFront();
ListNode*
old = front;
front
= front->Next;
delete
old;
return
frontItem;
}
#endif
主程序源代码:
#include
#include"QueueLi.h"
using
namespace std;
int
main()
{
Queue
myQ;
myQ.enqueue(10);
myQ.enqueue(20);
myQ.enqueue(30);
cout
<< myQ.getFront() << endl;
myQ.dequeue();
cout
<< myQ.getFront() << endl;
cout
<< myQ.dequeue() << endl;
cout
<< myQ.dequeue() << endl;
return
0;
}
运行结果: