循环队列(c语言)

  在循环队列中,Q->front==Q->rear 并不能确定队列为空,也有可能是队列已满,所以采用“队列头指针在队列尾指针的下一位置”来判断队列已满(此方法会浪费一个内存空间)。

《数据结构(C语言版)[严蔚敏_吴伟民]》中63页有讲解。

  此程序,在书中例子的基础上,增加了内存空间不足的重新分配。

define.h

 1 // define.h
 2 #ifndef __MENGQL_DEFINE__
 3 #define __MENGQL_DEFINE__
 4 
 5 #define C_LOG_DBG(format, ...) 
 6 //printf("[%s@%s,%d] " format ,__FUNCTION__, __FILE__, __LINE__, ##__VA_ARGS__);
 7 #define C_LOG_ERR(format, ...) printf("[%s@%s,%d] " format ,__FUNCTION__, __FILE__, __LINE__, ##__VA_ARGS__);
 8 typedef enum EStatus {ERROR, OK} Status;
 9 
10 #endif

SqQueue.h

 1 // SqQueue.h
 2 #ifndef __SQ_QUEUE_H__
 3 #define __SQ_QUEUE_H__
 4 
 5 #include "define.h"
 6 #define MAXQSIZE 100
 7 
 8 typedef struct
 9 {
10     QElemType *base;
11     int front;
12     int rear;
13     int queuesize;
14 }SqQueue;
15 
16 #endif

SqQueue.c

// SqQueue.c
typedef int QElemType;
#include "SqQueue.h"
#include <stdio.h>
#include <stdlib.h>

Status InitQueue(SqQueue *Q)
{
    Q->queuesize = MAXQSIZE;
    Q->base = (QElemType *)malloc(Q->queuesize * sizeof(QElemType));
    if(Q->base == NULL)
    {
        C_LOG_ERR("%s", "malloc error!!!\n");
        return ERROR;
    }
    Q->front = Q->rear = 0;
    return OK;
}
int QueueLength(SqQueue *Q)
{
    return ((Q->rear - Q->front + Q->queuesize) % Q->queuesize);
}
Status EnQueue(SqQueue *Q, QElemType e)
{
    /*
    在循环队列中,Q->front==Q->rear 并不能确定,队列为空,也有可能是队列已满,
    所以采用“队列头指针在队列尾指针的下一位置”来判断队列已满(此方法会浪费一个内存空间)。
    数据结构(C语言版)[严蔚敏_吴伟民]中63页有讲解。
    */
    C_LOG_DBG("[%d][%d][%d]\n", Q->rear, Q->queuesize, Q->front);
    if((Q->rear+1) % Q->queuesize == Q->front)
    {
        Q->base = (QElemType *)realloc(Q->base, Q->queuesize * 2 * sizeof(QElemType));
        if(Q->base == NULL)
        {
            C_LOG_ERR("%s", "malloc error!!!\n");
            return ERROR;
        }
        Q->queuesize *= 2;
    }
    Q->base[Q->rear] = e;
    Q->rear = (Q->rear+1) % Q->queuesize;
    return OK;
}

Status DeQueue(SqQueue *Q, QElemType *e)
{
    if(Q->front == Q->rear)
    {
        C_LOG_ERR("%s", "queue is empty!!!\n");
        return ERROR;
    }
    *e = Q->base[Q->front];
    Q->front = (Q->front+1) % Q->queuesize;
    return OK;
}
Status DestroyQueue(SqQueue *Q)
{
    free(Q->base);
    return OK;
}
int main()
{
    SqQueue Q;
    QElemType e;
    int i;
    InitQueue(&Q);
    for(i=0; i<MAXQSIZE*10; ++i)
    {
        C_LOG_DBG("%d\n", i);
        if(EnQueue(&Q, i) != OK)
        {
            return -1;
        }
    }
    while(Q.front != Q.rear)
    {
        DeQueue(&Q, &e);
        printf("%d\n", e);
    }
    DestroyQueue(&Q);
    return 0;
}

posted on 2012-08-21 17:29  favourmeng  阅读(3162)  评论(0编辑  收藏  举报

导航