3.循环队列(数组)

来源:互联网 发布:java如何实现高并发 编辑:程序博客网 时间:2024/06/06 05:33
/* *      循环队列 * */#include <stdio.h>#include <stdlib.h>#define LEN 8typedef struct Queue {        int* pbase;        int front;      //头部        int rear;       //尾部}QUEUE;void init(QUEUE* pq);                   //初始化队列int in_queue(QUEUE* pq, int val);       //入队int out_queue(QUEUE* pq, int* pval);    //出队void traverse_queue(QUEUE* pq);         //遍历队列int empty_queue(QUEUE* pq);             //是否为空int full_queue(QUEUE* pq);              //是否已满int main(){        QUEUE q;        int val;        init(&q);        in_queue(&q, 1);         in_queue(&q, 2);        in_queue(&q, 3);        in_queue(&q, 4);        in_queue(&q, 5);        in_queue(&q, 6);        in_queue(&q, 7);        traverse_queue(&q);        if (out_queue(&q, &val))                printf("出队成功,出队元素是:%d\n", val);        else                printf("出队失败!\n");                traverse_queue(&q);        return 0;}/*初始化*/void init(QUEUE* pq){        pq->pbase = (int*)malloc(sizeof(int) * LEN);        pq->front = 0;          //头部        pq->rear = 0;           //尾部}/*是否为空*/int empty_queue(QUEUE* pq){        if (pq->front == pq->rear)                return 1;        else                return 0;}/*是否已满*/int full_queue(QUEUE* pq){        if ((pq->rear+1)%LEN == pq->front)                return 1;        else                return 0;}/*入队*/int in_queue(QUEUE* pq, int val){        if (full_queue(pq))                return 0;        else {                pq->pbase[pq->rear] = val;      //元素入队                pq->rear = (pq->rear+1)%LEN;    //更新尾部指向                                return 1;        }}/*出队*/int out_queue(QUEUE* pq, int* pval){        if (empty_queue(pq))                return 0;        else {                *pval = pq->pbase[pq->front];   //保存出队元素                pq->front = (pq->front+1)%LEN;  //更新头部指向                return 1;        }}/*遍历队列*/void traverse_queue(QUEUE* pq){        int tmp;        tmp = pq->front;        while (tmp != pq->rear) {                printf("%d ", pq->pbase[tmp]);                tmp = (tmp+1)%LEN;        }        printf("\n");}

原创粉丝点击