问题描述
队列操作题。根据输入的操作命令,操作队列(1)入队、(2)出队并输出、(3)计算队中元素个数并输出。
输入格式
第一行一个数字N。
下面N行,每行第一个数字为操作命令(1)入队、(2)出队并输出、(3)计算队中元素个数并输出。
输出格式
若干行每行显示一个2或3命令的输出结果。注意:2.出队命令可能会出现空队出队(下溢),请输出“no”,并退出。
样例输入
7
1 19
1 56
2
3
2
3
2
样例输出
19
1
56
0
no
数据规模和约定
1<=N<=50
#include <iostream>
#include <cstdlib>
#define ERROR -10000
using namespace std;
typedef struct Node *PtrToNode;
typedef int ElementType;
struct Node { /* 队列中的结点 */
ElementType Data;
PtrToNode Next;
};
typedef PtrToNode Position;
struct QNode {
Position Front, Rear; /* 队列的头、尾指针 */
int Size; /* 队列元素数量 */
};
typedef struct QNode *Queue;
bool Isempty(Queue Q)
{
return(Q->Size==0);
}
int Getlen(Queue Q)
{
return (Q->Size);
}
Queue create(Queue Q)
{
/*Q->Front=(struct Node*)malloc(sizeof(struct Node));
Q->Rear=Q->Front=NULL; */
Q=(struct QNode*)malloc(sizeof(struct QNode));
Q->Front=NULL;
Q->Rear=NULL;
Q->Size=0;
return Q;
}
void AddQ( Queue Q,int item)
{
PtrToNode P;
P=(struct Node*)malloc(sizeof(struct Node));
P->Data=item;
if(Q->Rear==NULL)
{
Q->Front=P;
Q->Rear=P;
}else
{
Q->Rear->Next=P;
Q->Rear=P;
}
P->Next=NULL;
Q->Size++;
}
int Delete(Queue Q)
{
int data;
Position P;
if(Q->Size==0)
return ERROR;
data=Q->Front->Data;
P=Q->Front;
if(Q->Size==1)
{
free(Q->Front);
Q->Front=NULL;
Q->Rear=NULL;
}else
{
Q->Front=P->Next;
free(P);
}
Q->Size--;
return data;
}
void print(Queue Q)
{
Position p;
p=Q->Front;
while(p)
{
cout<<p->Data<<" ";
p=p->Next;
}
cout<<endl;
}
int main()
{
int n,chose,rs,num;
Queue Q=NULL;
Q=create(Q);
/*AddQ(Q,19);
AddQ(Q,56);
AddQ(Q,6);
AddQ(Q,7);
AddQ(Q,5);
print(Q);
cout<<Delete(Q)<<endl;
Delete(Q);
Delete(Q);
Delete(Q);
print(Q);*/
cin>>n;
for(int i=0;i<n;i++)
{
cin>>chose;
switch(chose)
{
case 1:
cin>>num;
AddQ(Q,num);
break;
case 2:
rs=Delete(Q);
if(rs==ERROR)
{
cout<<"no"<<endl;
return 0;
}
else{
cout<<rs<<endl;
}
break;
case 3:
cout<<Getlen(Q)<<endl;
break;
}
}
return 0;
}