赞
踩
数组形式的队列在插入元素时有两种方法,第一种是将所有元素前移,但这样会耗费很多资源,另一种方式是将头指针向后移动,但这样移动到队尾时将无法继续插入元素。而链表插入删除数据时不需要移动数据,因此链表形式的队列在工程中兴起。下面是其C++的具体实现。
1.结点结构
- typedef int DataType; //队列中的元素类型
- typedef struct _QNode //结点结构
- {
- DataType data;
- struct _QNode *next;
- }QNode;
-
- typedef QNode *QueuePtr;
2.队列定义
- typedef struct Queue
- {
- int length; //队列的长度
- QueuePtr front; //队头指针
- QueuePtr rear; //队尾指针
- }LinkQueue;
3.队列的初始化
- void InitQueuue(LinkQueue *LQ)
- {
- if(!LQ) return;
- LQ->length=0;
- LQ->front=LQ->rear=NULL;
- }
4.判断队列是否为空
- int IsEmpty(LinkNode *LQ)
- {
- if(!LQ) return 0;
- if(LQ->front==NULL) return 1;
- return 0;
- }
5.判断队列是否为满
- int IsFull(LinkNode *LQ)
- {
- if(!LQ) return 0;
- if(LQ->length==MaxSize) return 1;
- return 0;
- }
6.入队,将元素data插入到队列中
- int InsertQueuue(LinkQueue *LQ,DataType data)
- {
- if(!LQ) return 0;
- if(IsFull(LQ)) return 0;
- QNode *qNode=new QNode;
- qNode->data=data;
- qNode->next=NULL;
- if(IsEmpty(LQ))
- {
- LQ->front=LQ->rear=qNode;
- }
- else
- {
- LQ->rear->next=qNode; //在队尾插入新节点qNode
- LQ->rear=qNode; //队尾指向新插入的节点
- }
- LQ->Length++;
- return 1;
- }

7.出队,将元素data移出队列
- int DeleteQueuue(LinkQueue *LQ,DataType data)
- {
- if(!LQ) return 0;
- if(IsFull(LQ)) return 0;
- if(!data) return 0;
-
- tmp=LQ->front;
- LQ->front=tmp->next;
- if(!LQ->front) LQ->rear=NULL; //如果队头出列以后不存在其他元素,则rear节点也要置空
-
- *data=tmp->data; //将出队元素存储到*data
- LQ->length--;
-
- delete tmp;
- return 1;
- }

8.清空队列
- void ClearQueue(LinkQueue *LQ)
- {
- if(!LQ) return;
- while(LQ->front)
- {
- QueuePtr tmp=LQ->front->next;
- delete LQ->front;
- LQ->front=tmp;
- }
- LQ->front=LQ->rear=0;
- LQ->length=0;
- }
赞
踩
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。