数据结构.队列(C语言实现)

来源:互联网 发布:java支付开发demo 编辑:程序博客网 时间:2024/04/29 19:27

#include<stdio.h>

#include<stdlib.h>

#include<malloc.h>

#define Status int
#define OK    1
#define ERROR    0
#define    QElemType    int

typedef struct QNode {
    QElemType    data;
    struct     QNode    *next;
}QNode,    *QueuePtr;

typedef    struct {
    QueuePtr    front;
    QueuePtr    rear;
}LinkQueue;



//Init queue

Status    InitQueue(LinkQueue *Q)
{
    Q->front=Q->rear=(QueuePtr)malloc(sizeof(QNode));
    if(!Q->front)
    {
        printf("****** malloc failed ******");
        return ERROR;
    }

    Q->front->next=NULL;
    return OK;

}


/*delete Queue*/
Status DestoryQueue(LinkQueue *Q)
{
    while (Q->front)
    {
        Q->rear = Q->front->next;
        free(Q->front);
        Q->front=Q->rear;
    }
    return OK;

}


/*enqueue*/
Status    EnQueue(LinkQueue *Q, QElemType e)
{
    QueuePtr    p=NULL;
    p=(QueuePtr)malloc(sizeof(QNode));
    if (!p)
    {
        printf("****** malloc failed ******");
        return ERROR;
    }
    p->data = e;
    p->next = NULL;
    Q->rear->next=p;
    Q->rear=p;
    
    return OK;
}

// Dequeue
Status DeQueue(LinkQueue *Q, QElemType e)
{
    QueuePtr    p;
    if (Q->front == Q->rear)
        return ERROR;

    p=Q->front->next;
    e=p->data;
    printf("\n%d is take out from Queue!\n",e);
    Q->front->next= p->next;
    
    if (Q->rear == p)
        Q->rear = Q->front;
        
    free(p);
    return OK;        
}

int main(void)
{
        LinkQueue    Q1;
        int i,n,e;
        char ch,ch2;
        int mark;
        /*if ((InitQueue(&Q1)) == OK)
            printf("Init success !\n");
        else
            printf("****** Fail to init Queue !\n");
        */
        InitQueue(&Q1);
        
        printf("Please input value for n:    ");
        scanf("%d",&n);
        
        for (i=1; i <= n; ++i)
        {
            printf("input values(e) for number %d:\t", i);
            scanf("%d",&e);
            if ((EnQueue(&Q1,e)) != OK)
                break;
        }
        printf("###### data fill queue! \n#######");
        sleep(1);
        
        /*printf("Do you want to delete Queue ?     Y|y/N|n");
        scanf("%c",&ch);
        if (ch =='Y' | ch=='y')
            mark=1;
        else
            mark=0;
        if (mark)
            DeQueue(&Q1,e);
        mark=0;*/
        
        /*
        printf("Do you want to destory Queue ?     Y|y/N|n");
        scanf("%c",&ch2);
        if (ch2 =='Y' | ch2=='y')
            mark=1;
        else
            mark=0;
        if (mark)
            DestoryQueue(&Q1);
        mark=0;
        */            
        while (n>0)
        {
            DeQueue(&Q1,e);
            n--
        }

        return 0;

}

原创粉丝点击