编辑代码

#include <stdio.h>
#include "windows.h"

typedef int E;

struct LNode {
    E element;
    struct LNode *Next;
};

typedef struct LNode *Node;

struct Queue {
    Node front, rear;
};

typedef struct Queue *LQueue;

BOOL initQueue(LQueue queue) {
    queue->front = queue->rear = malloc(sizeof(struct LNode));
    if (queue->front == NULL) return 0;
    return 1;
}

// 链表队push方法
BOOL pushQueue(LQueue queue, E element) {
    Node NewNode = malloc(sizeof(struct LNode));    //  申请Node空间
    if (NewNode == NULL) return 0;  //空间不足返回Null
    NewNode->element = element;
    queue->rear->Next = NewNode;
    queue->rear = NewNode; //rear加指向NewNode
    return 1;
}

// 判断链表队是否为空
BOOL isEmpty(LQueue queue) {
    return queue->rear == queue->front;
}

E popQueue(LQueue queue) {
    if (isEmpty(queue)) return -1; //判断队是否空,队空则返回-1
    queue->front = queue->front->Next;
    return queue->front->element;
}

//遍历方法
void f(LQueue queue) {
    printf(">>>");
    Node tmp = queue->front;
    do {
        if (isEmpty(queue)) {       //判断队是否为空,为空则不进行遍历,强行遍历会发生错误,不存在的node会随机指向一个Node
            printf("队为空<<<\n");
            return;
        }
        queue->front = queue->front->Next;
        printf("%d ", queue->front->element);
    } while (queue->front != queue->rear);
    queue->front = tmp;
    printf("<<<\n");
}

int main() {
    struct Queue queue;
    initQueue(&queue);
    for (int i = 1; i < 6; ++i) {
        pushQueue(&queue, i * 100);
    }
    f(&queue);
    while (!isEmpty(&queue)) {
        printf("%d ", popQueue(&queue));
    }
    f(&queue);
}