时间:2022-11-03 10:29:59 | 栏目:C代码 | 点击:次
队列的定义
队列实现的方式有两种
队列需要实现的函数
T dequeue() : 出队列,并返回取出的元素void enqueue(const T &t) : 入队列T &head() : 获取队首数据,但是不会被取出const T &head() const : 获取const类型队首数据int length() const: 获取数量(父类已经实现)void clear(): 清空队列(父类已经实现)本章,我们实现的队列基于链表形式实现,它的父类是我们之前实现的LinkedList类:
所以Queue.h代码如下:
#ifndef QUEUE_H
#define QUEUE_H
#include "throw.h"
// throw.h里面定义了一个ThrowException抛异常的宏,如下所示:
//#include <iostream>
//using namespace std;
//#define ThrowException(errMsg) {cout<<__FILE__<<" LINE"<<__LINE__<<": "<<errMsg<<endl; (throw errMsg);}
#include "LinkedList.h"
template < typename T>
class Queue : public LinkedList<T>
{
public:
inline void enqueue(const T &t) { LinkedList<T>::append(t); }
inline T dequeue()
{
if(LinkedList<T>::isEmpty()) { // 如果栈为空,则抛异常
ThrowException("Stack is empty ...");
}
T t = LinkedList<T>::get(0);
LinkedList<T>::remove(0);
return t;
}
inline T &head()
{
if(LinkedList<T>::isEmpty()) { // 如果栈为空,则抛异常
ThrowException("Stack is empty ...");
}
return LinkedList<T>::get(0);
}
inline const T &head() const
{
if(LinkedList<T>::isEmpty()) { // 如果栈为空,则抛异常
ThrowException("Stack is empty ...");
}
return LinkedList<T>::get(0);
}
};
#endif // QUEUE_H
int main(int argc, char *argv[])
{
Queue<int> queue;
cout<<"******* current length:"<<queue.length()<<endl;
for(int i = 0; i < 5; i++) {
cout<<"queue.enqueue:"<<i<<endl;
queue.enqueue(i);
}
cout<<"******* current length:"<<queue.length()<<endl;
while(!queue.isEmpty()) {
cout<<"queue.dequeue:"<<queue.dequeue()<<endl;
}
return 0;
}
运行打印:
