#include<stdio.h>
#include<stdlib.h>
struct queue{
int *data;
int front,rear;
int maxsize;
};
struct queue *create(int maxSize){
struct queue *q;
q=(struct queue *)malloc(sizeof(struct queue));
q->data=malloc(sizeof(int)*maxSize);
q->front=q->rear=0;
q->maxsize=maxSize;
return q;
}
void inqueue(struct queue *q,int num){/*入队*/
if((q->rear+1)%q->maxsize==q->front){
printf("queue is full\n");
return;
}
q->data[q->rear++]=num;
q->rear=q->rear%q->maxsize;
}
int dequeue(struct queue *q){/*出队*/
if(q->front==q->rear){
printf("queue is empty\n");
exit(-1);
}
int temp = q->data[q->front++];
q->front=q->front%q->maxsize;
return temp;
}
int main(){
struct queue *q;
int n=10;
q=create(n);
for(int i=0;i<n-1;i++){/*队列能用的空间为n-1*/
inqueue(q,i);
}
for(int i=0;i<n-1;i++){
printf("%d\t",dequeue(q));
}
printf("\n");
struct queue *q2;
int n2=10;
q2=create(n2);
for(int i=0;i<n2;i++){/*最多n-1,插多了就会插不进*/
inqueue(q2,i);
}
for(int i=0;i<n2;i++){
printf("%d\t",dequeue(q2));
}
}
C语言之队列(不记录size,用(rear+1)%maxsize==front判断队满,会浪费一个空间,实际容量为maxsize-1)
最新推荐文章于 2023-05-25 21:01:14 发布