#include <stdio.h> #include <stdlib.h> struct Node { int value; struct Node* next; }; typedef struct Node Node; struct Queue { Node *front; Node *rear; int size; }; typedef struct Queue Queue; // // Created by 李东明 on 2020/7/31. // #include <stdio.h> #include <stdlib.h> #include "node.h" #ifndef TEST2_QUEUE_H #define TEST2_QUEUE_H struct Queue { Node *front; Node *rear; int size; }; typedef struct Queue Queue; // 建立一个节点 Node *createQueueNode(int value) { Node *node = (Node *) malloc(sizeof(Node)); node->value = value; node->next = NULL; return node; } // 建立一个空队列 Queue *createQueue() { Queue *queue = (Queue *) malloc(sizeof(Queue)); queue->front = (Node *) malloc(sizeof(Node)); queue->front->next = NULL; queue->rear = queue->front; queue->size = 0; } // 添加一个节点 void push(Queue *queue, Node *node) { queue->rear->next = node; queue->rear = queue->rear->next; queue->size++; } // 弹出一个节点 void pop(Queue *queue) { if (queue->size <= 0) { printf("this queue is empty!"); return; } Node *node = queue->front; queue->front = queue->front->next; queue->size--; free(node); } // 得到队头的节点 Node *front(Queue *queue) { if (queue->size <= 0) return NULL; return queue->front->next; } // 得到队尾的节点 Node *back(Queue *queue) { if (queue->size <= 0) return NULL; return queue->rear; } // 得到当前的队列元素个数 int size(Queue *queue) { return queue->size; } // 检查队列是否为空 int isEmpty(Queue *queue) { return queue->size <= 0; } // 清空队列 void clear(Queue *queue) { Node *node = NULL; while (!isEmpty(queue)) { node = queue->front; queue->front = queue->front->next; free(node); } free(queue->front); // 释放最后一个节点的内存 free(queue); } int main() { Queue *queue = createQueue(); Node *pNode = createQueueNode(10); push(queue, pNode); pNode = createQueueNode(20); push(queue, pNode); pNode = createQueueNode(30); push(queue, pNode); printf("%d\n", front(queue)->value); printf("%d\n", back(queue)->value); while (!isEmpty(queue)) { printf("%d->", front(queue)->value); pop(queue); } clear(queue); return 0; }
原文:https://www.cnblogs.com/li1234567980/p/13417779.html