源码
#include <inttypes.h>
#include <stdio.h>
#include <stdlib.h>
typedef int E;
struct LNode {
E element;
struct LNode * next;
};
typedef struct LNode * Node;
struct Queue {
Node front, rear;
};
typedef struct Queue * LinkQueue;
_Bool initQueue(LinkQueue queue) {
Node node = malloc(sizeof(struct LNode));
if (node == NULL) return 0;
queue->rear = queue->front = node;
return 1;
}
_Bool offerQueue(LinkQueue queue, E element) {
Node node = malloc(sizeof(struct LNode));
if (node == NULL) return 0;
node->element = element;
node->next = NULL;
queue->rear->next = node;
queue->rear = node;
return 1;
}
_Bool isEmpty(LinkQueue queue) {
return queue->rear == queue->front;
}
E pollQueue(LinkQueue queue) {
Node tmp = queue->front->next;
E e = tmp->element;
queue->front->next = queue->front->next->next;
if (queue->rear == tmp) queue->rear = queue->front;
free(tmp);
return e;
}
void printQueue(LinkQueue queue) {
printf("<<< ");
Node node = queue->front->next;
while (node) {
printf("%d ", node->element);
node = node->next;
}
printf("<<<\n");
}
int main() {
struct Queue queue;
initQueue(&queue);
for (int i = 0; i < 8; ++i) {
offerQueue(&queue, i + 1);
}
printQueue(&queue);
while (!isEmpty(&queue)) {
printf("%d ", pollQueue(&queue));
}
}