队列的基本操作(采用链式存储结构)

队列的初始化、入队、出对、销毁队列。

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

#define TRUE 1
#define FALSE 0
#define ERROR -1

typedef int Status;
typedef char ElemType;
typedef struct qNode
{
    ElemType data;
    struct qNode *next;
} QNode,*QueuePtr;
typedef struct 
{
    QueuePtr front,rear;
} QueueLink;

Status InitQueue(QueueLink *q);
Status InsertQueue(QueueLink *q,ElemType e);
Status DeleteQueue(QueueLink *q,ElemType *e);
Status DestroyQueue(QueueLink *q);

int main(int argc,char **argv)
{
    QueueLink q;
    InitQueue(&q);
    int i,j;
    for(i=0;i<6;i++)
    {
        InsertQueue(&q,i+65);
    }
    char ch;
    for(j=0;j<6;j++)
    {
        DeleteQueue(&q,&ch);
        printf("%c,",ch);
    }
    printf("\n");
    DestroyQueue(&q);
    exit(0);
}

Status InitQueue(QueueLink *q)
{
    q->front=q->rear=(QueuePtr)malloc(sizeof(QNode));
    if(!q->front)
        return ERROR;
    q->front->next=NULL;
    return TRUE;
}
//入队
Status InsertQueue(QueueLink *q,ElemType e)
{
    QueuePtr p=(QueuePtr)malloc(sizeof(QNode));
    if(!p)
        return ERROR;
    p->data=e;
    p->next=NULL;
    q->rear->next=p;
    q->rear=p;
    return TRUE;
}
//出对
Status DeleteQueue(QueueLink *q,ElemType *e)
{
    if(q->front==q->rear)
        return     FALSE;
    QueuePtr p=q->front->next;
    *e=p->data;
    q->front->next=p->next;
    if(q->rear==p)
        q->rear=q->front;
    free(p);
    return TRUE;
}

Status DestroyQueue(QueueLink *q)
{
    while(q->front)
    {
        q->rear=q->front->next;
        free(q->front);
        q->front=q->rear;
    }
    return TRUE;
}


你可能感兴趣的:(队列,链式存储结构)