【数据结构与算法】(四) c 语言静态队列的简单实现

//
//  main.c
//  testQueue
//
//  Created by lan on 16/3/12.
//  Copyright © 2016年 lan. All rights reserved.
//

/*
    静态队列:用数组实现
    静态队列通常必须是循环队列
    因为:无论是出队还是入队,头指针和尾指针都必须只加不减
         如果不是循环队列,之前分配的内存不能再次使用
*/

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

typedef struct Queue {
    int * pBase;
    int front;
    int rear;
}QUEUE, * PQUEUE;

void init(PQUEUE);
bool en_queue(PQUEUE, int);
bool out_queue(PQUEUE, int *);
bool is_empty(PQUEUE);
bool is_full(PQUEUE);
void traverse(PQUEUE);

int main(int argc, const char * argv[]) {
    QUEUE Q;
    int val;
    
    init(&Q);
    
    if (is_empty(&Q)) {
        printf("队列为空\n");
    }
    
    en_queue(&Q, 1);
    en_queue(&Q, 2);
    en_queue(&Q, 3);
    en_queue(&Q, 4);
    en_queue(&Q, 5);
    en_queue(&Q, 6);
    en_queue(&Q, 7);
    
    if ( is_full(&Q)) {
        printf("队列已满\n");
    }
    traverse(&Q);

    out_queue(&Q, &val);
    printf("出队列的值 = %d\n", val);
    traverse(&Q);
    out_queue(&Q, &val);
    printf("出队列的值 = %d\n", val);
    traverse(&Q);
}

void init(PQUEUE pQ) {
    pQ->pBase = (int *)malloc(sizeof(int) * 6);
    //实际有效元素只有 5 个,其中留出 1 个方便对队列进行操作
    // 如果不留出一个元素,当frout == rear 不能判断队列是空还是满
    if (NULL == pQ->pBase) {
        printf("内存分配失败,程序退出!\n");
        exit(-1);
    }
    pQ->front = 0;
    pQ->rear = 0;
    return;
}

bool en_queue(PQUEUE pQ, int val) {
    if (is_full(pQ)) {
        return false;
    }
    
    pQ->pBase[pQ->rear] = val;
    pQ->rear = (pQ->rear + 1) % 6;
    return true;
}

bool out_queue(PQUEUE pQ, int * pVal) {
    if (is_empty(pQ)) {
        return false;
    }
    
    *pVal = pQ->pBase[pQ->front];
    pQ->front = (pQ->front + 1) % 6;
    return true;
}

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

bool is_full(PQUEUE pQ) {
    if ((pQ->rear + 1) % 6 == pQ->front) {
        return true;
    } else {
        return false;
    }
}

void traverse(PQUEUE pQ) {
    printf("遍历队列: ");
    int cnt = pQ->front;
    while (cnt != pQ->rear) {
        printf("%d ", pQ->pBase[cnt]);
        cnt = (cnt + 1) % 6;
    }
    printf("\n");
}


输出结果:

队列为空
队列已满
遍历队列: 1 2 3 4 5 
出队列的值 = 1
遍历队列: 2 3 4 5 
出队列的值 = 2
遍历队列: 3 4 5 
Program ended with exit code: 0


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值