/*队列的数组实现*/
/*BUPT OJ 第三次培训B题*/
#include<iostream>
#include<string>
#define MAX_SIZE 80000
using 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;
else
return 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;
else
return 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;
}
运行结果: