队列的实现及相关操作

2020-01-26  本文已影响0人  Jorunk
typedef struct QNode {
    ElemType data;      
     struct QNode *next;
} QNode, *QueuePrt;

typedef struct {
    QueuePrt front, rear; // 队头、尾指针
} LinkQueue;

initQueue(LinkQueue *q)
{
    q->front=q->rear=(QueuePtr)malloc(sizeof(QNode));
    if( !q->front )
        exit(0);
    q->front->next = NULL;
}


InsertQueue(LinkQueue *q, ElemType e)
{
    QueuePtr p;
    p = (QueuePtr)malloc(sizeof(QNode));
    if( p == NULL )
        exit(0);
    p->data = e;
    p->next = NULL;
    q->rear->next = p;
    q->rear = p;
}

DeleteQueue(LinkQueue *q, ELemType *e)
{
    QueuePtr p;
    if( q->front == q->rear )
        return;
    p = q->front->next;
    *e = p->data;
    q->front->next = p->next;
    if( q->rear == p )
        q->rear = q->front;
    free(p);
}

DestroyQueue(LinkQueue *q)
{
    while( q->front ) {
        q->rear = q->front->next;
        free( q->front );
        q->front = q->rear;
}
}


定义一个循环队列
#define MAXSIZE 100
typedef struct
{
    ElemType *base; // 用于存放内存分配基地址
            // 这里你也可以用数组存放
    int front;
    int rear;
}

initQueue(cycleQueue *q)
{
    q->base = (ElemType *) malloc (MAXSIZE *                           sizeof(ElemType));
    if( !q->base )
        exit(0);
    q->front = q->rear = 0;
}

InsertQueue(cycleQueue *q, ElemType e)
{
    if( (q->rear+1)%MAXSIZE == q->front )
        return; // 队列已满
    q->base[q->rear] = e;
    q->rear = (q->rear+1) % MAXSIZE;
}

DeleteQueue(cycleQueue *q, ElemType *e)
{
    if( q->front == q->rear )
        return ; // 队列为空
    *e = q->base[q->front];
    q->front = (q->front+1) % MAXSIZE;
}

上一篇 下一篇

猜你喜欢

热点阅读