队列的顺序实现(c语言)

#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;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值