(摘自大话数据结构)线性表—队列的链式存储结构->出队&入队&建立空队列

#include <stdio.h>
#include <stdlib.h>
#define OK 1
#define ERROR 0
#define TRUE 1
#define FALSE 0
#define MAXSIZE 20
#define OVERFLOW 0
typedef int Status;
typedef int QElemType;
typedef struct QNode//标识符和类型名一样不知道什么用意。。
{
    QElemType data;
    struct QNode *next;
}QNode,*QueuePtr;
typedef struct//这没写标识符
{
    QueuePtr front,rear;
}LinkQueue;
Status InitQueue(LinkQueue *Q);
Status EnQueue(LinkQueue *Q,QElemType e);
Status QueueTraverse(LinkQueue Q);
Status DeQueue(LinkQueue *Q,QElemType *e);
int main()
{
    LinkQueue l;
    int num;
    InitQueue(&l);
    EnQueue(&l,3333);
    QueueTraverse(l);
    printf("\n%d",DeQueue(&l,&num));
    printf("\n%d",num);
    return 0;
}
Status InitQueue(LinkQueue *Q)//不用malloc()野指针也是随便指向一个地址的,用了malloc()是也是随机分配了一个地址,不同就是地址大小确定?
{
    Q->front=Q->rear=(QueuePtr)malloc(sizeof(QNode));
    Q->front->next=NULL;
    Q->rear=Q->front;
    return OK;
}
Status EnQueue(LinkQueue *Q,QElemType e)
{
    QueuePtr q;
    q=(QueuePtr)malloc(sizeof(QNode));//要新建一个结点,所以sizeof()里要放QNode
    if(!q)
        exit(OVERFLOW);//我觉得这应该是正常运行程序并退出程序,你们认为这该是0还是非0?
    q->data=e;
    q->next=NULL;
    Q->rear->next=q;
    Q->rear=q;
    return OK;
}
Status QueueTraverse(LinkQueue Q)
{
    QueuePtr p;
    p=Q.front->next;
    while(p)
    {
        printf("%d ",p->data);
        p=p->next;
    }
    return OK;
}
Status DeQueue(LinkQueue *Q,QElemType *e)
{
    if(Q->front==Q->rear)
        return ERROR;
    QueuePtr p;
    p=Q->front->next;
    *e=p->data;
    Q->front->next=p->next;
    if(Q->rear==p)
        Q->rear=Q->front;
    free(p);
    return OK;
}

实战BUG:

1.在创建空队列时没有建立新结点,导致Q->front和Q->rear成了野指针,然而,编译器并没有报错O_O

疑惑:

1.exit()OVERFLOW宏定义问题,关于exit()见http://www.cnblogs.com/laojie4321/archive/2012/03/31/2426910.html

2.关于NULL越看越懵逼了+_+如果只针对malloc()的话见这位大佬的文章最后的第九条。http://www.cnblogs.com/youxin/archive/2012/03/27/2420023.html

posted @ 2017-01-23 18:01  路人姜。  阅读(257)  评论(0编辑  收藏  举报