数据结构里循环队列

2017-11-12  本文已影响0人  梦在原点
#include<stdio.h>
#include<stdlib.h>
#include<malloc.h>
#define MAX 10
typedef struct Queue
{
    int* pBase;//可以看作数组
    int front;
    int rear;
}QUEUE;

void init(QUEUE*);
bool enQueue(QUEUE*,int);
void travel_queue(QUEUE*);
bool full_queue(QUEUE*);

int main(void)
{
    QUEUE Q;
    init(&Q);
    enQueue(&Q,1);
    enQueue(&Q,2);
    enQueue(&Q,3);
    enQueue(&Q,4);
    enQueue(&Q,5);
    enQueue(&Q,6);
    travel_queue(&Q);
    return 0;
}

void init(QUEUE *pQ)
{
    pQ->pBase=(int *)malloc(sizeof(int )*MAX);//开辟队列且定义长度,长度是MAX
    pQ->front=0;
    pQ->rear=0;
}

bool full_queue(QUEUE* pQ)
{
    if((pQ->rear+1)%MAX==pQ->front)
        return true;
    else
        return false;
}

bool enQueue(QUEUE* pQ,int val)
{
    if(full_queue(pQ))
    {
        return false;
    }
    else
    {
        pQ->pBase[pQ->rear]=val;
        pQ->rear=(pQ->rear+1)%MAX;
        return true;
    }
}

void travel_queue(QUEUE* pQ)
{
    int i=0;
    i=pQ->front;
    while(i!=pQ->rear)
    {
        printf("%d \n",pQ->pBase[i]);
        i=(i+1)%MAX;
    }
    return;
}
上一篇 下一篇

猜你喜欢

热点阅读