【C数据结构】简单顺序队列代码

    技术2022-07-14  82

     

    #include<stdio.h> #include<stdlib.h> #define MAXLEN 10 typedef int datatype; typedef struct{ datatype data[MAXLEN]; int front;//头 int rear;//尾 }SeqQueue; /* 队头front+1是头元素下标,队尾rear是尾元素下标 */ void InitQueue(SeqQueue *&Q); int InQueue(SeqQueue *&Q,datatype x); void OutQueue(SeqQueue *&Q,datatype &x); int Length_Queue(SeqQueue *Q); int IsEmpty(SeqQueue *Q); int IsFull(SeqQueue *Q); void ReadFront_Q(SeqQueue *&Q,datatype &x);//读取队头 void ReadRear_Q(SeqQueue *&Q,datatype &x);//读取队尾 int main(){ SeqQueue *Q; int x_F,x_R,x; InitQueue(Q); printf("队长:%d ",Length_Queue(Q)); printf("判断是否空? %d , 判断是否满? %d\n",IsEmpty(Q),IsFull(Q)); for(int i=0;i<10;i++){ //入队5个元素 InQueue(Q,i+1); ReadFront_Q(Q,x_F); ReadRear_Q(Q,x_R); printf("当前队头:%d,当前队尾:%d\n",x_F,x_R); } //MAXLEN=10,此时队满 printf("队长:%d ",Length_Queue(Q)); printf("判断是否空? %d , 判断是否满? %d\n\n",IsEmpty(Q),IsFull(Q)); for(int i=0;i<3;i++){ //出队3个元素 OutQueue(Q,x); ReadFront_Q(Q,x_F); ReadRear_Q(Q,x_R); printf("当前队头:%d,当前队尾:%d,出队元素:%d\n",x_F,x_R,x); } printf("队长:%d ",Length_Queue(Q)); printf("判断是否空? %d , 判断是否满? %d\n\n",IsEmpty(Q),IsFull(Q)); for(int i=0;i<7;i++){ //出队7个元素 OutQueue(Q,x); ReadFront_Q(Q,x_F); ReadRear_Q(Q,x_R); printf("当前队头:%d,当前队尾:%d,出队元素:%d\n",x_F,x_R,x); } printf("队长:%d ",Length_Queue(Q)); printf("判断是否空? %d , 判断是否满? %d\n",IsEmpty(Q),IsFull(Q)); } void InitQueue(SeqQueue *&Q){ Q=new SeqQueue; Q->front=Q->rear=-1; } int InQueue(SeqQueue *&Q,datatype x){ //入队 -成功返回1,失败返回0 if(IsFull(Q))//队满 return 0; //队未满 Q->data[++Q->rear]=x;//尾先自增 return 1; } void OutQueue(SeqQueue *&Q,datatype &x){ //出队 if(!IsEmpty(Q)) x=Q->data[++Q->front];//头先自增 } int Length_Queue(SeqQueue *Q){ return Q->rear-Q->front; } int IsEmpty(SeqQueue *Q){ return Q->rear==Q->front; } int IsFull(SeqQueue *Q){ //满返回1,未满返回0 if(Length_Queue(Q)>=MAXLEN) return 1; return 0; } void ReadFront_Q(SeqQueue *&Q,datatype &x){ if(!IsEmpty(Q)) x=Q->data[Q->front+1]; } void ReadRear_Q(SeqQueue *&Q,datatype &x){ if(!IsEmpty(Q)) x=Q->data[Q->rear]; }

     

    Processed: 0.011, SQL: 9