队列也是一种常见的线性表,它和栈相比有以下不同:
#include<iostream> #include<queue> #include<iomanip> using namespace std; #define MAXSIZE 10 typedef int ElemType; //类定义 class SqQueue //顺序队列 { private: ElemType *base; int front; //队头指针 int rear; //对尾指针 public: SqQueue(); //构造函数 ~SqQueue(); //析构函数 void clear(); //请空队列 bool empty(); //队列是否为空 int size(); //获取队列大小 bool push(const ElemType &); //入队,队为满,返回false bool pop(); //出队,队为空,返回false const ElemType top(); //获取队头元素 const ElemType back(); //获取队尾元素 void queueTraverse(); //队列的遍历 }; //类实现 SqQueue::SqQueue() //构造函数 { base=new ElemType[MAXSIZE]; front=rear=0; } SqQueue::~SqQueue() //析构函数 { delete[]base; } void SqQueue::clear() //请空队列 { rear=front; } bool SqQueue::empty() //队列是否为空 { return front==rear; } int SqQueue::size() //获取队列大小 { return (rear-front+MAXSIZE)%MAXSIZE; } bool SqQueue::push(const ElemType &data) //入队,队为满,返回false { /* 另一种判断队满的方法 size() == MAXSIZE; */ if((rear+1)%MAXSIZE==front) //队满判断 return false; base[rear]=data; rear=(rear+1)%MAXSIZE; return true; } bool SqQueue::pop() //出队,队为空,返回false { if(empty()) return false; front=(front+1)%MAXSIZE; return true; } const ElemType SqQueue::top() //获取队头元素 { if(empty()) { cerr<<"队空!"<<endl; exit(0); } else return base[front]; } const ElemType SqQueue::back() //获取队尾元素 { if(empty()) { cerr<<"队空!"<<endl; exit(0); } return base[(rear-1+MAXSIZE)%MAXSIZE]; } void SqQueue::queueTraverse() //队列的遍历 { if(empty()) cout<<"队空,无法遍历!"<<endl; else { int p=front; while(p!=rear) { cout<<setw(4)<<base[p]; p=(p+1)%MAXSIZE; } cout<<endl; } }主函数
int main() { cout<<"循环顺序队列演练"<<endl; SqQueue queue; ElemType data; printf("入队,输入0结束!\n"); while(cin>>data && data) { if(!queue.push(data)) { printf("队已满,无法入队了!\n"); break; } } cout<<"遍历"<<endl; queue.queueTraverse(); cout<<"获取队头元素 "<<queue.top()<<endl; cout<<"获取队尾元素 "<<queue.back()<<endl; data=77; cout<<"队头出队,"<<data<<" 入队。"<<endl; queue.pop(); queue.push(data); cout<<"遍历"<<endl; queue.queueTraverse(); cout<<"再次入队"<<endl; while(cin>>data && data) { if(!queue.push(data)) { printf("队已满,无法入队了!\n"); break; } } cout<<"遍历"<<endl; queue.queueTraverse(); cout<<"队清空后,是否为空:"; queue.clear(); queue.empty()?cout<<"Yes!"<<endl:cout<<"No!"<<endl; cout<<"清空后,遍历"<<endl; queue.queueTraverse(); cout<<"获取队头元素:"; queue.top(); system("pause"); return 0; }运行:
原文地址:http://blog.csdn.net/zhangxiangdavaid/article/details/29195859