链式队列的实现

来源:互联网 发布:淘宝助理教程 编辑:程序博客网 时间:2024/06/05 23:05
#include <stdio.h>#include <stdlib.h>#define ElementType inttypedef struct Node{ElementType data;struct Node* next;}QNode;typedef struct {QNode * rear;QNode * front;int isEmpty;}Queue;const ElementType ERROR = -1;int ERRORFLAG = 0;/***创建一个队列 */Queue * CreateQueue() {Queue * queue = (Queue *)malloc(sizeof(Queue));queue->rear = NULL;queue->front = NULL;queue->isEmpty = 1;return queue;}/***添加元素到队列 */void Add(ElementType x, Queue * q) {QNode * pNode = (QNode*)malloc(sizeof(QNode));pNode->data = x;pNode->next = NULL;if (q->isEmpty) {//队列为空 q->rear = pNode;q->front = pNode;q->isEmpty = 0;return;}q->rear->next = pNode;q->rear = pNode;}/***从队列中删除*返回出队列的值*若队列为空 ERRORFLAG 为 1 */ElementType Delete(Queue * q) {ElementType ele;QNode * pNode;ERRORFLAG = 0;if (q->isEmpty) {printf("队列为空\n");ERRORFLAG = 1;return ERROR;} ele = q->front->data; pNode = q->front;  //如果front 与 rear指向相同//即到了最后一个元素  if (pNode == q->rear) { q->isEmpty = 1; free(pNode); return ele; } q->front = q->front->next;free(pNode);return ele;}/***返回队列的长度 */ int Length(Queue * q) {QNode * front = q->front;QNode * rear = q->rear;int len = 0;while (front != rear) {front = front->next;len ++;}if (!q->isEmpty)len ++;return len;}/***打印队列信息 */ void Print(Queue * q) {QNode * front = q->front;QNode * rear = q->rear;printf("队列的长度:%d\n",Length(q));while (front != rear) {printf("%d ",front->data);front = front->next;}printf("%d ",front->data);printf("\n");}int main() {Queue * q = CreateQueue();Add(10,q);Add(11,q);Add(12,q);Add(13,q);Add(14,q);printf("%d\n",Delete(q));printf("%d\n",Delete(q));printf("%d\n",Delete(q));printf("%d\n",Delete(q));printf("%d\n",Delete(q));printf("%d\n",Delete(q));printf("%d\n",Delete(q));Print(q);return 0;}

0 0