用数组和链表实现队列操作
来源:互联网 发布:it薪资排行 编辑:程序博客网 时间:2024/05/17 04:09
/*队列的数组实现*//*BUPT OJ 第三次培训B题*/#include<iostream>#include<string>#define MAX_SIZE 80000using namespace std;class Queue {private:int queue[MAX_SIZE];int head;int tail;public:Queue(): head(0),tail(0){}void push(int data){if(tail==MAX_SIZE){cout<<"Push error!"<<endl;}else{queue[tail]=data;tail++;}}void pop(){if(head==tail){cout<<"Pop error!"<<endl;}else{head++;}}int front(){if(head==tail){cout<<"front error!"<<endl;}else{return queue[head];}}bool empty(){if(size()==0)return true;elsereturn false;}int size(){return tail-head;}void clear(){head=tail=0;}}q;int main(){string operation;string errstr("operation error!");while(true){cin>>operation;if(operation=="end") break;else if(operation=="push"){int x;cin>>x;q.push(x);}else if(operation=="pop"){if(q.empty()) cout<<errstr<<endl;else q.pop();}else if(operation=="front"){if(q.empty()) cout<<errstr<<endl;else cout<<q.front()<<endl;}else if(operation=="clear"){q.clear();}else if(operation=="size"){cout<<q.size()<<endl;}}return 0;}
/*队列的链表实现*/#include<iostream>#include<string>using namespace std;struct Node{int data;Node *next;Node(): next(NULL){}Node (int value):data(value),next(NULL){}};class Queue {private:Node *head;Node *tail;int node_count;public:Queue(): head(0),tail(0),node_count(0){}~Queue(){clear();}void push(int data){Node *newnode=new Node(data);if(newnode==NULL){/*new结点失败*/cout<<"Push error!"<<endl;}else{if(tail==NULL){/*如果当前队列为空*/ head=tail=newnode;}else{/*如果不为空,新节点放在链表结尾*/tail->next=newnode;/*尾指针指向newnode*/ tail=newnode;/*移动尾指针*/}node_count++;}}void pop(){if(head==NULL){cout<<"pop error!"<<endl;}else{/*删除链表头结点*/Node *temp=head;head=head->next;delete temp;if(head==NULL){/*队列为空*/tail=NULL;}node_count--;}}int front(){if(head==NULL){/*队列为空*/cout<<"front error!"<<endl;}else{return head->data;;}}bool empty(){if(size()==0)return true;elsereturn false;}int size(){return node_count;}void clear(){while(size()!=0) pop();}}q;int main(){string operation;string errstr("operation error!");while(true){cin>>operation;if(operation=="end") break;else if(operation=="push"){int x;cin>>x;q.push(x);}else if(operation=="pop"){if(q.empty()) cout<<errstr<<endl;else q.pop();}else if(operation=="front"){if(q.empty()) cout<<errstr<<endl;else cout<<q.front()<<endl;}else if(operation=="clear"){q.clear();}else if(operation=="size"){cout<<q.size()<<endl;}}return 0;}
运行结果:
0 0
- 用数组和链表实现队列操作
- 队列的数组和链表实现
- 队列01:数组和链表实现
- java 实现数组队列和链表队列
- 分别用数组和链表实现队列
- 队列可以用数组和链表实现
- C++实现队列--数组实现和链表实现
- C++实现队列--数组实现和链表实现
- 队列(数组实现和链表实现)
- 利用数组实现队列操作
- 基于数组和链表的队列实现
- 利用数组和链表实现优先队列
- FIFO 队列的链表和数组实现
- 队列的两种实现:数组和链表
- FIFO 队列的链表和数组实现
- FIFO 队列的链表和数组实现
- 用数组实现堆栈和队列
- 用数组实现堆栈和队列
- exit函数的妙用
- py2exe使用教程(五)——指定额外文件
- Session简介,创建与销毁
- CC150:将一个矩阵旋转90度
- H264 pps sps作用
- 用数组和链表实现队列操作
- 接口于类型信息-类型信息
- Android ffmpeg H264 YUV显示
- DLL注入
- C# 16进制与字符串、字节数组之间的转换
- 三、四柱汉诺塔问题
- JAVA程序设计(15.3)----- 图形用户界面GUI 制作挂钟
- Spring事务的隔离级别
- 病毒木马查杀实战第004篇:熊猫烧香之专杀工具的编写