链队列
来源:互联网 发布:儿童学编程 编辑:程序博客网 时间:2024/05/22 06:39
链队列是队列的链式表示和实现。主要操作包括:初始化、清空、销毁、判断是否为空、插入、删除、队列长度、获取队头元素。在实现的过程中,在队列的结构中添加了count,用来记录队列中元素的个数,这样无论在判定是否为空、求队列长度以及其他操作的实现中都可以简化。
#include <stdio.h>#include <stdlib.h>#include <malloc.h>#define OK 1#define ERROR 0#define OVERFLOW -1typedef struct QNode{ int data; struct QNode *next;}QNode;typedef struct{ QNode *front;//队头指针 QNode *rear;//队尾指针 int count;//队列元素个数}LinkQueue;//队列初始化int InitQueue(LinkQueue *Q){ Q->front = Q->rear = (QNode *)malloc(sizeof(QNode)); if(!Q->front) exit(OVERFLOW); Q->rear->next =NULL; Q->count = 0; return OK;}//销毁队列int DestroyQueue(LinkQueue *Q){ while(Q->front) { Q->rear = Q->front->next; free(Q->front); Q->front = Q->rear; } return OK;}//清空队列int ClearQueue(LinkQueue *Q){ while(Q->front->next->next) { Q->front->next = Q->front->next->next; free(Q->front); } free(Q->front->next); Q->front->next = NULL; Q->rear = Q->front; Q->count = 0; return OK;}//判断队列是否为空int QueueEmpty(LinkQueue *Q) { if (Q->count == 0) printf("Queue is empty\n"); else printf("Queue is not empty\n"); return 0; }//队列长度 int QueueLength(LinkQueue *Q) { int n; n = Q->count; return n; }//获取队头元素int GetHead (LinkQueue *Q){ int n; QNode *P; if (QueueLength(Q)==0) { printf("Queue don't have Head\n"); } else { P = Q->front->next; n = P->data; } return n;}//插入int InsertQueue(LinkQueue *Q, int n){ QNode *P; P=(QNode *)malloc(sizeof(QNode)); if(!P) exit(OVERFLOW); P->data = n; P->next = NULL; Q->rear->next = P; Q->rear = P; Q->count ++; return OK;}//删除int DeleteQueue(LinkQueue *Q){ QNode *P; int n; if(Q->front == Q->rear) return ERROR; P = Q->front->next; n = P->data; Q->front->next = P->next; if(Q->rear == P) Q->rear = Q->front; free(P); Q->count --; return 0;}int main(){ LinkQueue *Q; int i,k; Q=(LinkQueue*)malloc(sizeof(LinkQueue)); InitQueue(Q); int quit=1; while(quit==1) { printf("1.Insert 2.Delete 3.GetHead 4.QueueLength 5.Empty 6.Clear 7.Destroy\n"); scanf("%d",&k); getchar(); switch(k) { case 1: printf("Insert number \n"); scanf("%d",&i); InsertQueue(Q,i); break; case 2: printf("Delete number is "); DeleteQueue(Q); printf("\n"); break; case 3: printf("Queue head is %d\n",GetHead(Q)); break; case 4: printf("Queue length is %d\n",QueueLength(Q)); break; case 5: QueueEmpty(Q); case 6: ClearQueue(Q); QueueEmpty(Q); break; case 7: DestroyQueue(Q); break; } } return 0;}
0 0
- 队列-循环队列/链队列
- 队列,链队列,循环队列
- 队列,链队列,循环队列
- 队列--链表队列
- 队列之链队列
- 08.队列.链队列
- 队列,链队列,链式存储的队列
- 队列---循环队列与链队列比较
- 顺序队列 - 循环队列 - 链队列
- 链队列
- 链队列
- 链队列
- 链队列
- 链队列
- 链队列
- 链队列
- 链队列
- 链队列
- Num 31 : HDOJ : 1863 畅通工程 [ kruskal( 克鲁斯卡尔 )算法 ] [ 最小生成树 ]
- UTF-8
- 编程小技巧
- 使用Genymotion调试出现错误 不能装软件 应用未安装
- popupwindows用例
- 链队列
- hdoj 1863 畅通工程
- 21-IO流-17-IO流(字符流-缓冲区-自定义MyBufferedReader-readLine方法)
- ZigBee路由协议分析(机制,算法,发现,建立)
- APP搜索附近功能的一种解决方案-基于百度LBS云服务
- 黑马程序员-集合框架(二)
- 21-IO流-18-IO流(字符流-缓冲区-装饰设计模式)
- Android AnimationDrawable动画与APP启动引导页面
- 杭电1879继续畅通工程