队列的链式表示和实现
2015-10-25 18:44
531 查看
用链表表示的队列简称为链队列。一个链队列显然需要两个分别指示队头和队尾的指针(分别称为头指针和尾指针)才能唯一确定。和线性表的单链表一样,为了操作方便起见,我们也给链队列添加一个头结点,并令头指针指向头结点。由此,空的链队列的判断条件为头指针和尾指针均指向头结点,如图所示//- - - - - - - - - -单链队列——队列的链式存储结构- - - - - - - - -
typedef struct QNode{ int date; struct QNode *next; }QNode,*QueuePtr; typedef struct{ QueuePtr Front; //队头指针 QueuePtr rear; //队尾指针 }LinkQueue;//InitQueue
//构造一个空队列Q int InitQueue(LinkQueue &Q){ Q.Front=Q.rear=(QueuePtr)malloc(sizeof(QNode)); if(!Q.Front) exit(OVERFLOW); Q.Front->next=NULL; return OK; }//DestoryQueue
//销毁队列Q int DestoryQueue(LinkQueue &Q){ while(Q.Front){ Q.rear=Q.Front->next; free(Q.Front); Q.Front=Q.rear; } return OK; }//EnQueue
//插入元素e为Q的新的队尾元素 int EnQueue(LinkQueue &Q,int e){ QNode *p; p=(QueuePtr)malloc(sizeof(QNode)); if(!p) exit(OVERFLOW); p->date=e; p->next=NULL; Q.rear->next=p; Q.rear=p; return OK; }//Dequeue//删除Q的队头元素,用e返回其值int DeQueue(LinkQueue &Q,int &e){if(Q.Front==Q.rear)return ERROR;QNode *p;p=Q.Front->next;e=p->date;Q.Front->next=p->next;if(Q.rear==p)Q.rear=Q.Front;free(p);return OK;}//QueueLength//返回队列的长度int QueueLength(LinkQueue Q){QNode *p;p=Q.Front;int i=0;while(p!=Q.rear){p=p->next;i++;}return i;}//QueueTraverse//遍历队列Qint QueueTraverse(LinkQueue Q){int l=QueueLength(Q);for(int i=0;i<l;i++){Q.Front=Q.Front->next;printf("%d ",Q.Front->date);}printf("\n");}//main<pre name="code" class="cpp">int main(){LinkQueue Q;InitQueue(Q);int e;printf("Please input elem:\n");while(~scanf("%d",&e)){EnQueue(Q,e);}printf("Output:\n");QueueTraverse(Q);}//结果预览
相关文章推荐
- Lua教程(七):数据结构详解
- 解析从源码分析常见的基于Array的数据结构动态扩容机制的详解
- C#数据结构揭秘一
- 数据结构之Treap详解
- JavaScript数据结构和算法之图和图算法
- Java数据结构及算法实例:冒泡排序 Bubble Sort
- Java数据结构及算法实例:插入排序 Insertion Sort
- Java数据结构及算法实例:考拉兹猜想 Collatz Conjecture
- java数据结构之java实现栈
- java数据结构之实现双向链表的示例
- Java数据结构及算法实例:选择排序 Selection Sort
- Java数据结构及算法实例:朴素字符匹配 Brute Force
- Java数据结构及算法实例:汉诺塔问题 Hanoi
- Java数据结构及算法实例:快速计算二进制数中1的个数(Fast Bit Counting)
- java数据结构和算法学习之汉诺塔示例
- Java数据结构及算法实例:三角数字
- Java数据结构之简单链表的定义与实现方法示例
- 数据结构之AVL树详解
- qqwry.dat的数据结构图文解释第1/2页
- JavaScript中数据结构与算法(五):经典KMP算法