#include <stdio.h>
#include <stdlib.h>
#define MAXSIZE 100
typedef struct SqQueue{
int *base;
int front;
int rear;
}SqQueue;
/*初始化*/
SqQueue * initQueue(){
SqQueue * sqQueue = (SqQueue *)malloc(sizeof(SqQueue));
sqQueue -> base = (int*)malloc(sizeof(int) * MAXSIZE);
sqQueue -> front = sqQueue -> rear = 0;
return sqQueue;
}
/*入队*/
int enQueue(SqQueue * sqQueue, int elem){
if((sqQueue -> rear + 1) % MAXSIZE == sqQueue -> front) return 0; //队满
*(sqQueue -> base + sqQueue -> rear) = elem;
sqQueue -> rear = (sqQueue -> rear + 1) % MAXSIZE;
return 1;
}
/*出队*/
int deQueue(SqQueue * sqQueue){
if(sqQueue -> front == sqQueue -> rear) return 0;//队空
int f = sqQueue -> front;
sqQueue -> front = (sqQueue -> front + 1) % MAXSIZE;
return *(sqQueue -> base + f);
}
/*取头元素*/
int getHead(SqQueue * sqQueue){
if(sqQueue -> front != sqQueue -> rear){
return *(sqQueue -> base + sqQueue -> front);
}
return 0;
}
/*求队内元数个数*/
int getQueueLen(SqQueue * sqQueue){
return (sqQueue -> rear - sqQueue -> front + MAXSIZE) % MAXSIZE;
}
int main()
{
SqQueue * sqQueue = initQueue();
enQueue(sqQueue,100);
enQueue(sqQueue,200);
enQueue(sqQueue,300);
printf("显示当前队内所有元素:\n");
int queueLen = getQueueLen(sqQueue);
for(int i = 0; i < queueLen;i ++){
printf("%d ",getHead(sqQueue));
deQueue(sqQueue);
}
printf("\n");
// printf("现在长度为:%d\n",getQueueLen(sqQueue));
// printf("现在队头元素:%d\n",getHead(sqQueue));
// printf("删除元素队头:%d\nn",deQueue(sqQueue));
// printf("现在队头元素:%d\n",getHead(sqQueue));
// printf("删除元素队头:%d\n",deQueue(sqQueue));
// printf("现在队头元素:%d\n",getHead(sqQueue));
return 0;
}
队列的顺序实现(c语言)
最新推荐文章于 2024-08-02 09:32:48 发布