数组实现的MyQueue顺序队列

作者在 2017-04-24 18:49:44 发布以下内容
#include<iostream>
#include<cstdlib>
using namespace std;

typedef struct Queue
{
int *Array;
int Front,Rear;
}*MyQueue;

MyQueue Create(void);    //创建一个队列 
int IsEmpty(MyQueue Q);  //检验是否为空栈 
void DeQueue(MyQueue Q); //出队 
void EnQueue(int X,MyQueue Q); //入队 
void GetQueueFront(MyQueue Q); //获取队头元素 
void GetQueueRear(MyQueue Q);  //获取队尾元素 

int main()  //测试 
{
MyQueue Q=Create();
EnQueue(100,Q);
DeQueue(Q);
return 0;
}

int IsEmpty(MyQueue Q)
{
return Q->Front==Q->Rear;   //如果队头下标等于队尾下标,也就是空队列那么返回1,否则返回0 
}

void EnQueue(int X,MyQueue Q)
{
if(Q->Front==Q->Rear&&Q->Rear==0)  //如果是空队列 
{
Q->Array[Q->Front]=X;     //从头部入列
Q->Array[Q->Rear]=Q->Array[Q->Front];     //空队列入队的话,队头也是队尾 
cout <<Q->Array[Q->Front] <<"已入列" <<"入队后" ;
}
else        //如果不是空队列 
{
Q->Array[++Q->Rear]=X; //从尾部入列 
cout <<X <<"已入列" <<endl <<"入队后 " ;    //提示 
}
GetQueueFront(Q);
GetQueueRear(Q);
cout <<endl ; 
}

void DeQueue(MyQueue Q)         
{
if(IsEmpty(Q))
   cout <<"队列为空不能出列 " <<endl ;       //如果是空队列不能出列 
else
   {
    Q->Array[Q->Front]=Q->Array[Q->Front++];  //队头往后一个元素挪 
}
cout <<"出队后" ;     //提示 
GetQueueFront(Q);
GetQueueRear(Q);
}

MyQueue Create(void)
{
MyQueue Q;
Q->Front=Q->Rear=0;   //初始化队列 
int a[8]={18,19,11,13,25,26,30,14};
for(int i=0;i<8;i++)
{
if(i==0)   //一开始的先入队头 
{
Q->Array[Q->Front]=a[i];
Q->Array[Q->Rear]=Q->Array[Q->Front];  //一开始队尾也是队头 
cout <<Q->Array[Q->Rear]<<"已入列 " <<endl ;  //提示 
}
else        //有了队头后就从队尾入队 
   {
Q->Array[++Q->Rear]=a[i]; //从尾部入列 
    cout <<Q->Array[Q->Rear]<<"已入列 " <<endl ;//提示 
}
}
cout <<endl ;
GetQueueFront(Q);
GetQueueRear(Q);
cout <<endl ;
return Q;
}

void GetQueueFront(MyQueue Q)
{
if(IsEmpty(Q))
   cout <<"空队列!" <<endl ;
else
   cout <<Q->Array[Q->Front] <<"为队头 " <<endl ; //Front就是队头 
}

void GetQueueRear(MyQueue Q)
{
if(IsEmpty(Q))
   cout <<"空队列!" <<endl ;
else
   cout <<Q->Array[Q->Rear] <<"为队尾 " <<endl ; //Rear就是队尾 
}
c++基础 | 阅读 1126 次
文章评论,共0条
游客请输入验证码