链队列实现代码

#include <stdio.h>

#define OK 1
#define ERROR 0

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

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

int EnQueue(LinkQueue *Q, int e)
{
    QueuePtr s = (QueuePtr)malloc(sizeof(QNode));
//    if(!s)                //空间分配失败
//    {
//        exit(1);
//    }
    s->data = e;
    s->next = NULL;
    
    Q->rear->next = s;       //让拥有新元素e的新节点成为当前队列尾节点的后继
    Q->rear = s;              //让当前队列的尾指针指向新的尾节点s。
    return OK;
}

int DeQueue(LinkQueue *Q, int *e)
{
    QueuePtr p = (QueuePtr)malloc(sizeof(QNode));
    
    if(Q->front == Q->rear)
    {
        return ERROR;
        printf("当前队列为空\n");
    }
    p = Q->front->next;
    *e = p->data;
    Q->front->next = p->next;   //将原队头节点的后继赋值给头结点的后继
    
    if(Q->rear == p)   //如果队头就是队尾
    {
        Q->rear = Q->front;             //删除队头节点后为空队列
    }
    free(p);
    
    return OK;
}

int main()
{
    int e = 0;
    LinkQueue Q;
    EnQueue(&Q, 100);
    DeQueue(&Q, &e);
    
    //printf("%d\n", e);
    
    return 0;
}

猜你喜欢

转载自blog.csdn.net/zwt0112/article/details/81190192