数据结构之队列的创建与操作(五)

队列的数组结构

#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>

/*定义一个队列*/
typedef struct Queue{
    int *pBase;//此为一个静态链表,用的是数组,pBase指向的是数组第一个元素地址
    int front;//front居然是个整型
    int rear;
}QUEUE, *PQUEUE;


void initQueue(PQUEUE pQueue, int length);//初始化一个队列
bool pushQueue(PQUEUE pQueue, int value, int length);//入队
bool isEmptyQueue(PQUEUE pQueue);//是否为空
bool isFullQueue(PQUEUE pQueue, int length);//是否满
bool popQueue(PQUEUE pQueue, int *pValue, int length);//出队
void showQueue(PQUEUE pQueue, int length);//展示队列

int main(int argc, const char * argv[]) {
    QUEUE queue;
    int length = 6;
    initQueue(&queue, length);
    
    pushQueue(&queue, 1, length);
    pushQueue(&queue, 12, length);
    pushQueue(&queue, 19, length);
    showQueue(&queue, length);
    
    int value = 0;
    if (popQueue(&queue, &value, length)) {
        printf("出栈成功,出栈的值为:%d\n", value);
    }else{
        printf("出栈失败!");
    }
    
    showQueue(&queue, length);
    return 0;
}

void initQueue(PQUEUE pQueue, int length)
{
    pQueue->pBase = (int *)malloc(sizeof(int) * length);
    if (NULL == pQueue->pBase) {
        printf("分配空间失败!");
        exit(-1);
    }else{
        pQueue->rear = 0;
        pQueue->front = 0;
    }
}

bool pushQueue(PQUEUE pQueue, int value, int length)
{
    if (isFullQueue(pQueue, length)) {
        return false;
    }else{
        //第一步,将入队的值赋值给rear指向的元素的数据域
        pQueue->pBase[pQueue->rear] = value;
        //或者 *(pQueue->pBase + pQueue->rear) = value;
        
        //第二步,rear = (rear + 1)%数组长度
        pQueue->rear = (pQueue->rear + 1)%length;
        return true;
    }
}

bool popQueue(PQUEUE pQueue, int *pValue, int length)
{
    if (isEmptyQueue(pQueue)) {
        return false;
    }else{
        //第一步,将front指向的元素的数据域赋值给pValue指向的位置
        *pValue = pQueue->pBase[pQueue->front];
        //第二步,front = (front + 1)%数组长度
        pQueue->front = (pQueue->front + 1)%length;
        return true;
    }
}

bool isEmptyQueue(PQUEUE pQueue)
{
    if (pQueue->front == pQueue->rear) {
        return true;
    }else{
        return false;
    }
}

bool isFullQueue(PQUEUE pQueue, int length)
{
    if (pQueue->front == (pQueue->rear + 1)%length) {
        return true;
    }else{
        return false;
    }
}

void showQueue(PQUEUE pQueue, int length)
{
    if (isEmptyQueue(pQueue)) {
        return;
    }else{
        int tempFront = pQueue->front;
        printf("该队列里面的值分别为:");
        while (tempFront != pQueue->rear) {
            printf("%d ", pQueue->pBase[tempFront]);
            tempFront = (tempFront + 1)%length;
        }
        printf("\n");
    }
}

队列的链式结构

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值