数据结构-循环队列(先入先出)

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

#define QUEUE_LENGTH         10
typedef int ElementType;

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

static void init(QUEUE *);
static bool en_queue(QUEUE *, ElementType);
static void traverse_queue(QUEUE *);
static bool full_queue(QUEUE *);
static bool out_queue(QUEUE *, ElementType *);
static bool empty_queue(QUEUE *);

int main(int argc, char *argv[])
{
    printf("hello world\r\n");

    QUEUE Q;
    int val;

    init(&Q);

    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);
    en_queue(&Q, 8);

    traverse_queue(&Q);

    if (out_queue(&Q,&val))
        printf("out queue success value = %d\r\n", val);
    else
        printf("out queue failed\r\n");

    traverse_queue(&Q);
    
    if (out_queue(&Q,&val))
        printf("out queue success value = %d\r\n", val);
    else
        printf("out queue failed\r\n");

    traverse_queue(&Q);
    
    return 0;
}

void init(QUEUE *pQ)
{
   pQ->pBase = (ElementType *)malloc(sizeof(ElementType) * QUEUE_LENGTH); 

   if (pQ->pBase == NULL)
   {
        printf("init malloc failed\r\n");
   }

   pQ->front = 0;
   pQ->rear = 0;
}

bool en_queue(QUEUE *pQ, ElementType val)
{
    if (full_queue(pQ))
    {
        return false;
    }

    pQ->pBase[pQ->rear] = val;
    pQ->rear = (pQ->rear + 1) % QUEUE_LENGTH;

    return true;
}

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

void traverse_queue(QUEUE *pQ)
{
    int i = pQ->front;

    while (i != pQ->rear)
    {
        printf("%d", pQ->pBase[i]);
        i = (i + 1) % QUEUE_LENGTH;
    }

    printf("\r\n");

}

bool out_queue(QUEUE *pQ, ElementType *value)
{
    if (empty_queue(pQ))
        return false;

    *value = pQ->pBase[pQ->front];
    pQ->front = (pQ->front + 1) % QUEUE_LENGTH;

    return true;
}

bool empty_queue(QUEUE *pQ)
{
    if (pQ->front == pQ->rear)
        return true;   
    else
        return false;
}

/* out put
hello world
12345678
out queue success value = 1
2345678
out queue success value = 2
345678
*/

/************* end of file *********************/
发布了124 篇原创文章 · 获赞 21 · 访问量 3万+

猜你喜欢

转载自blog.csdn.net/tyustli/article/details/103605251
今日推荐