【数据结构】用C++编写队列及基本操作(包括插入,出队列,摧毁,清空等等)
2015-05-31 22:57
281 查看
//【数据结构】用C++编写队列及基本操作(包括插入,出队列,摧毁,清空等等) //头文件 #ifndef _SEQ_STACK_ #define _SEQ_STACK_ #include <iostream> using namespace std; template <class Type> class Queue { public: Queue(size_t sz = INIT_SIZE) { capacity = sz > INIT_SIZE ? sz : INIT_SIZE; base = new Type[capacity]; front = back = 0; } ~Queue() { destory(); } public: bool empty() const //判断是否为空 { return(front==back); } bool full()const //判断是否已满 { return((back+1)%capacity==front); } public: void push(const Type &x) //进队列 { if (full()) { cout << "队列已满,不能插入。" << endl; return; } base[back] = x; back = (back + 1) % capacity; } void pop() //出队列 { if (empty()) { cout << "队列为空" << endl; return; } front=(front+1)%capacity; } bool getFront(Type &x) const //获得队列头部 { if (empty()) { cout << "队列为空" << endl; return false; } else { x = base[front]; return true; } } int length() const //求大小 { return back-front; } void clear() //清除 { front=back=0; } void destory() //摧毁 { delete[]base; base = NULL; capacity = front = back = 0; } void show() const //显示 { if (empty()) { cout << "队列为空" << endl; return; } for (int i = front; i != back; i = (i + 1) % capacity) { cout << base[i] << endl; } } void quit_system(int &x) { x = 0; } private: enum { INIT_SIZE = 8 }; Type *base; int capacity; int front; int back; }; #endif //主函数 #include "Queue.h" void main() { Queue<int> myqueue; int select = 1; int Item; while (select) { cout << "***************************************" << endl; cout << "* [1] show [2] push *" << endl; cout << "* [3] pop [4] length *" << endl; cout << "* [5] clear [6] destory *" << endl; cout << "* [7] getFront [8] quit_system *" << endl; cout << "***************************************" << endl; cout << "请选择:>"; cin >> select; switch (select) { case 1: myqueue.show(); break; case 2: cout << "请输入要插入的值(-1结束):>"; while (cin >> Item, Item != -1) { myqueue.push(Item); } break; case 3: myqueue.pop(); break; case 4: cout << "大小为:" << myqueue.length() << endl; break; case 5: myqueue.clear(); break; case 6: myqueue.destory(); break; case 7: if (myqueue.getFront(Item)) cout << "头元素为:"<<Item << endl; else cout << "该数不存在." << endl; break; case 8: myqueue.quit_system(select); break; default: break; } } return; }
相关文章推荐
- 【数据结构】用C++编写栈及基本操作(包括入栈,出栈,获得栈顶,摧毁,清空等等)
- 【数据结构】用C++实现双循环链表的各种操作(包括头删,尾删,插入,逆序,摧毁,清空等等)
- 【数据结构】用C++实现双链表的各种操作(包括头删,尾删,插入,逆序,摧毁,清空等等)
- 数据结构与算法分析学习笔记(1)--排序
- 几种常见的【排序】与【数据结构】
- 设计包含min函数的栈。
- C++ 数据结构 双链表(模板类)
- 数据结构面试题总结8——数组:数组循环移位
- 数据结构之---C/C++实现稀疏矩阵的十字链表
- 【算法笔记】数据结构(一)
- 数据结构与算法分析-队列
- 数据结构与算法分析-栈
- 数据结构与算法分析-表
- 数据结构之---C语言实现矩阵的转置
- 数据结构教程 冒泡算法
- hdu 5249区间第k大(学习了下树状数组的搞法)
- 一个简单的数据结构举例——二叉树及…
- 一个简单的数据结构举例——快排结合…
- 【技术-数据结构与算法分析】一致性哈希算法与Java实现
- CodeForces 140C - New Year Snowmen(数据结构)