您的位置:首页 > 理论基础 > 数据结构算法

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

2013-10-01 15:00 791 查看
#include<stdio.h>

#include<stdlib.h>

#include<malloc.h>

#define Status int

#define OK    1

#define ERROR    0

#define    QElemtype    int

#define MAXSIZE    100

typedef struct {

    QElemtype    *base;

    int    front;

    int    rear;

}SqQueue;

/************************************

****** initialize cycle queue

*************************************/

Status    InitQueue(SqQueue *Q)

{

    Q->base =(QElemtype *)malloc(sizeof(QElemtype) * sizeof(QElemtype));

    if (! Q->front)

        return ERROR;

    Q->front = Q->rear = 0;

    

    return OK;

}

/*************************************

**** QueueLength    ************

***************************************/

int Queuelength(SqQueue    Q)

{

    return    (Q.rear    - Q.front + MAXSIZE) % MAXSIZE;

        

}

/*************************************

**** QueueLength    ************

***************************************/

void PrintQueue(SqQueue    *Q)

{

    QElemtype *a = Q->base;

    

    int front = Q->front;

    int rear = Q->rear;

    

    while (front != rear)

    {

        printf("%d\t\n",a[front]);

        front++;

    }

    

    printf("\n");

        

}
/*************************************

**** EnQueue    ************

***************************************/

Status EnQueue(SqQueue *Q, QElemtype e)

{

    if ((Q->rear+1) % MAXSIZE ==Q->front)         //cycle Queue is full

        return ERROR;                          

    

    Q->base[Q->rear] = e;

    Q->rear = (Q->rear + 1) % MAXSIZE;

    

    return OK;

}

/*************************************

**** DeQueue    ************

***************************************/

Status DeQueue(SqQueue *Q, QElemtype e)

{

    if (Q->front == Q->rear)

        return ERROR;

    e = Q->base[Q->front];

    printf("deleted %d\n",e);

    sleep(1);

    Q->front = (Q->front +1) % MAXSIZE;

    

    return OK;

}

int main(void)

{

    SqQueue    S;

    printf("main-begin %p\n",S.base);

    InitQueue(&S);

    

    int i = 0;

    for(; i < 10; ++i)

    {

        EnQueue(&S, i);

    }

    PrintQueue(&S);

    

    for(i=0; i < 5; ++i)

        DeQueue(&S,i);

    printf("main-end    %p\n",S.base);

    //free(S.base);

    printf("main-end-after free    %p\n",S.base);

    return OK;

    

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: