设为首页 加入收藏

TOP

[数据结构]用C++编写队列及基本操作(包括插入,出队列,摧毁,清空等等)
2015-11-21 01:00:40 来源: 作者: 【 】 浏览:1
Tags:数据结构 编写 队列 基本操作 包括 插入 摧毁 清空 等等
//【数据结构】用C++编写队列及基本操作(包括插入,出队列,摧毁,清空等等)

//头文件

#ifndef _SEQ_STACK_
#define _SEQ_STACK_


#include 
  
   
using namespace std;


template 
   
     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
    
      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 << "头元素为:"<
      
     
    
   
  
】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
分享到: 
上一篇hdu 5254(暴力) 下一篇[C/C++标准库]_[初级]_[计算结构..

评论

帐  号: 密码: (新用户注册)
验 证 码:
表  情:
内  容: