3个回答
展开全部
仅供参考,呵呵
#include <iostream.h>
#include <stdlib.h>
typedef int ElemType;
struct Queue{
ElemType *queue;
int front;
int rear;
int MaxSize;
};
void InitQueue(Queue &Q)
{ //初始化
Q.MaxSize=80;
Q.queue=(ElemType *)malloc(sizeof(ElemType)*Q.MaxSize);
Q.rear=0;
Q.front=0;
}
bool EmptyQueue(Queue Q)
{ //判空操作
return Q.front == Q.rear;
}
void EnQueue(Queue &Q,ElemType item)
{//入队操作
if((Q.rear+1)%Q.MaxSize==Q.front)
{
Q.queue=(ElemType *)realloc(Q.queue,2*Q.MaxSize*sizeof(ElemType));
if(Q.rear!=Q.MaxSize-1) {
for(int i=0; i<=Q.rear; i++)
Q.queue[i+Q.MaxSize]=Q.queue[i];
Q.rear=Q.rear+Q.MaxSize;
}
Q.MaxSize=2*Q.MaxSize;
}
Q.rear=(Q.rear+1)%Q.MaxSize;
Q.queue[Q.rear]=item;
}
ElemType OutQueue(Queue &Q)
{ //出队
if(Q.front==Q.rear)
{
cout<< "\n队列已空,无法删除!" <<endl;
exit(1);
}
Q.front=(Q.front+1)%Q.MaxSize;
return Q.queue[Q.front];
}
void ClearQueue(Queue &Q)
{ //清空
if (Q.queue!=NULL)
free(Q.queue);
Q.front=Q.rear=0;
Q.queue=NULL;
Q.MaxSize=0;
}
void main()
{
Queue q;
int i,x,n,a[80];
InitQueue(q);
if(EmptyQueue(q))
cout<<"\n队列为空!"<<endl;
else
cout<<"\n队列不为空!"<<endl;
cout<<"\n请输入队列中元素个数n:"<<endl;
cout<<"input your n=";
cin>>n;
cout<<"\n请输入"<<n<<"个数:"<<endl;
for(i=0;i<n;i++)
cin>>a[i];
for(i=0;i<n;i++)
EnQueue(q,a[i]);
cout<<"\n出队2个元素:"<<endl;
cout<<OutQueue(q)<<endl;
cout<<OutQueue(q)<<endl;
cout<<"\n入队一个元素:"<<endl;
cin>>x;
EnQueue(q,x);
cout<<"\n队列中元素出队:"<<endl;
while(!EmptyQueue(q))
cout<<OutQueue(q)<<endl;
ClearQueue(q);
}
#include <iostream.h>
#include <stdlib.h>
typedef int ElemType;
struct Queue{
ElemType *queue;
int front;
int rear;
int MaxSize;
};
void InitQueue(Queue &Q)
{ //初始化
Q.MaxSize=80;
Q.queue=(ElemType *)malloc(sizeof(ElemType)*Q.MaxSize);
Q.rear=0;
Q.front=0;
}
bool EmptyQueue(Queue Q)
{ //判空操作
return Q.front == Q.rear;
}
void EnQueue(Queue &Q,ElemType item)
{//入队操作
if((Q.rear+1)%Q.MaxSize==Q.front)
{
Q.queue=(ElemType *)realloc(Q.queue,2*Q.MaxSize*sizeof(ElemType));
if(Q.rear!=Q.MaxSize-1) {
for(int i=0; i<=Q.rear; i++)
Q.queue[i+Q.MaxSize]=Q.queue[i];
Q.rear=Q.rear+Q.MaxSize;
}
Q.MaxSize=2*Q.MaxSize;
}
Q.rear=(Q.rear+1)%Q.MaxSize;
Q.queue[Q.rear]=item;
}
ElemType OutQueue(Queue &Q)
{ //出队
if(Q.front==Q.rear)
{
cout<< "\n队列已空,无法删除!" <<endl;
exit(1);
}
Q.front=(Q.front+1)%Q.MaxSize;
return Q.queue[Q.front];
}
void ClearQueue(Queue &Q)
{ //清空
if (Q.queue!=NULL)
free(Q.queue);
Q.front=Q.rear=0;
Q.queue=NULL;
Q.MaxSize=0;
}
void main()
{
Queue q;
int i,x,n,a[80];
InitQueue(q);
if(EmptyQueue(q))
cout<<"\n队列为空!"<<endl;
else
cout<<"\n队列不为空!"<<endl;
cout<<"\n请输入队列中元素个数n:"<<endl;
cout<<"input your n=";
cin>>n;
cout<<"\n请输入"<<n<<"个数:"<<endl;
for(i=0;i<n;i++)
cin>>a[i];
for(i=0;i<n;i++)
EnQueue(q,a[i]);
cout<<"\n出队2个元素:"<<endl;
cout<<OutQueue(q)<<endl;
cout<<OutQueue(q)<<endl;
cout<<"\n入队一个元素:"<<endl;
cin>>x;
EnQueue(q,x);
cout<<"\n队列中元素出队:"<<endl;
while(!EmptyQueue(q))
cout<<OutQueue(q)<<endl;
ClearQueue(q);
}
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询