转:C语言队列

C语言队列(数组内核)

#include <stdio.h>
#include <stdbool.h>
#include <stdlib.h>
struct Queue{
    int *pBase;
    int front; //对头
    int rear; //对尾
    int len; //队列长度
};
void initQueue(struct Queue * q,int len); //初始化队列
bool inQueue(struct Queue * q); //入队
bool outQueue(struct Queue * q); //出队
bool isEmpty(struct Queue * q); //判断队列是否为空
bool isFull(struct Queue * q); //判断队列是否已满
void printList(struct Queue * q); //输出队列元素
void clearQueue(struct Queue * q); //清空队列元素

int main(int argc, char *argv[])
{
    struct Queue q;//就会开辟一个 struc Queue 类型的内存地址
    initQueue(&q, 5);
    while(inQueue(&q))
    {}
    printList(&q);
    outQueue(&q);
    outQueue(&q);
    while (inQueue(&q)){}
    printList(&q);
    clearQueue(&q);
    while(inQueue(&q)){}
    printList(&q);
    return 0;
}
//初始化队列
void initQueue(struct Queue *q,int len)
{
    q->pBase = (int *)malloc(sizeof(int)*len);
    q->len = len;
    q->front = 0;
    q->rear = 0;
}
//入队
bool inQueue(struct Queue *q)
{
    if(isFull(q))
    {
        return false;
    }
    printf("请输入要入队的元素:");
    scanf("%d",q->pBase+q->rear);
    q->rear = (q->rear+1)%q->len;
    return true;
}
//出队

bool outQueue(struct Queue *q)
{
    if(isEmpty(q))
    {
        return false;
    }
    printf("出队元素为:%d\n",*(q->pBase+q->front));
    q->front = (q->front+1)%q->len;
    return true;
}
//判断队列是否为空
bool isEmpty(struct Queue * q)
{
    if(q->front == q->rear)
    {
        printf("队列已空\n");
        return true;
    }
        return false;
}
//判断队列是否已满
bool isFull(struct Queue * q)
{
    if((q->rear+1)%q->len == q->front)
    {
        printf("队列已满\n");
        return true;
    }
    return false;
}
//输出队列元素
void printList(struct Queue * q)
{
    int temp = q->front;
    while((temp != q->rear) && !isEmpty(q))
    {
        printf("%d\n",*(q->pBase+temp));
        temp = (temp+1)%q->len;
    }
}
//清空队列元素
void clearQueue(struct Queue * q)
{
    while(!isEmpty(q))
    {
        q->front = (q->front+1)%q->len;
    }
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值