顺序队列的c++实现
2015-06-17 22:11
316 查看
顺序队列的初始化及对队列的操作保存在queue.h中
主函数
结果图
#ifndef QUEUE_H #define QUEUE_H template <class T> class Queue { public: Queue(int queuecapacity); bool Isempty(); void Front(); void Rear(); void Push(T item); void Pop(); private: T *queue; int front; int rear; int capacity; }; //利用构造函数初始化顺序队列 template <class T> Queue<T>::Queue(int queuecapacity) { if( queuecapacity<1) { throw "the capacity of queue must be >0"; } else { queue=new T[queuecapacity]; capacity=queuecapacity; front=rear=0; //牺牲front这个位置,这个位置不放元素 } } //元素进队列 template <class T> void Queue<T>::Push(T item) { if((rear+1)%capacity==front) { throw "the queue is full"; } else { rear=(rear+1)%capacity; queue[rear]=item; } } //出列 template <class T> void Queue<T>::Pop() { if(Isempty()) throw "the queue is empty"; front=(front+1)%capacity; } //判断队列是否为空 template <class T> inline bool Queue<T>::Isempty() { return front==rear; } //队首元素 template <class T> inline void Queue<T>::Front() { if(!Isempty()) { cout<<"队首元素为"<< queue[(front+1)%capacity]<<endl; } else { cout<< "the queue is empty"<<endl; } } //队尾元素 template <class T> inline void Queue<T>::Rear() { if(!Isempty()) { cout<<"队尾元素为"<< queue[rear]<<endl; } else { cout<< "the queue is empty"<<endl; } } #endif
主函数
#include "queue.h" #include<iostream> using namespace std; int main() { Queue<int> q(10); q.Push(1); q.Push(2); q.Push(3); q.Front(); q.Rear(); q.Pop(); q.Pop(); q.Pop(); q.Front(); q.Rear(); q.Push(4); q.Front(); q.Rear(); system("pause"); return 0; }
结果图
相关文章推荐
- 2048 c语言
- c++ dynamic_cast
- Longest Substring Without Repeating Character
- LeetCode—Remove Linked List Elements—C++
- C语言操作符和表达式以及数据类型提升实例以及疑惑
- LeetCode—Reverse Linked List—C++
- C++ TinyXml操作(含源码下载)
- CTime与COleDateTime的常用操作和比较
- C++第12章项目,ATM机模拟队列。
- C++第13章 类继承
- C++ 中拷贝构造函数被调用情况
- 万年历(C语言版)
- c语言笔记
- [转]100个经典C语言程序(益智类问题)
- C++ Primer第一章(submit 转换格式)
- C++ Primer第一章
- C++12.1.3 类定义----typedef同义词、成员函数重载、指明inline
- chapter13test2
- C++ 学习笔记一易忽略的地方
- chapter13test1