当前位置:   article > 正文

数据结构之队列(链表形式)——C++具体实现_队列链表实现c++

队列链表实现c++

        数组形式的队列在插入元素时有两种方法,第一种是将所有元素前移,但这样会耗费很多资源,另一种方式是将头指针向后移动,但这样移动到队尾时将无法继续插入元素。而链表插入删除数据时不需要移动数据,因此链表形式的队列在工程中兴起。下面是其C++的具体实现。

1.结点结构

  1. typedef int DataType; //队列中的元素类型
  2. typedef struct _QNode //结点结构
  3. {
  4. DataType data;
  5. struct _QNode *next;
  6. }QNode;
  7. typedef QNode *QueuePtr;

2.队列定义

  1. typedef struct Queue
  2. {
  3. int length; //队列的长度
  4. QueuePtr front; //队头指针
  5. QueuePtr rear; //队尾指针
  6. }LinkQueue;

3.队列的初始化

  1. void InitQueuue(LinkQueue *LQ)
  2. {
  3. if(!LQ) return;
  4. LQ->length=0;
  5. LQ->front=LQ->rear=NULL;
  6. }

4.判断队列是否为空

  1. int IsEmpty(LinkNode *LQ)
  2. {
  3. if(!LQ) return 0;
  4. if(LQ->front==NULL) return 1;
  5. return 0;
  6. }

5.判断队列是否为满

  1. int IsFull(LinkNode *LQ)
  2. {
  3. if(!LQ) return 0;
  4. if(LQ->length==MaxSize) return 1;
  5. return 0;
  6. }

6.入队,将元素data插入到队列中

  1. int InsertQueuue(LinkQueue *LQ,DataType data)
  2. {
  3. if(!LQ) return 0;
  4. if(IsFull(LQ)) return 0;
  5. QNode *qNode=new QNode;
  6. qNode->data=data;
  7. qNode->next=NULL;
  8. if(IsEmpty(LQ))
  9. {
  10. LQ->front=LQ->rear=qNode;
  11. }
  12. else
  13. {
  14. LQ->rear->next=qNode; //在队尾插入新节点qNode
  15. LQ->rear=qNode; //队尾指向新插入的节点
  16. }
  17. LQ->Length++;
  18. return 1;
  19. }

7.出队,将元素data移出队列

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

8.清空队列

  1. void ClearQueue(LinkQueue *LQ)
  2. {
  3. if(!LQ) return;
  4. while(LQ->front)
  5. {
  6. QueuePtr tmp=LQ->front->next;
  7. delete LQ->front;
  8. LQ->front=tmp;
  9. }
  10. LQ->front=LQ->rear=0;
  11. LQ->length=0;
  12. }

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/羊村懒王/article/detail/706996
推荐阅读
相关标签
  

闽ICP备14008679号