当前位置:   article > 正文

队列的存储方式

队列的存储方式

队列的顺序存储结构:

  1. #include<stdio.h>
  2. #define ElemType int
  3. #define MAXSIZE 5
  4. typedef struct Node {
  5. ElemType* base;
  6. int front;
  7. int rear;
  8. }QueueLink;
  9. QueueLink* Init(QueueLink* q) {
  10. q->base = new ElemType[MAXSIZE];
  11. q->front = q->rear = 0;
  12. return q;
  13. }
  14. QueueLink* enQueue(QueueLink* q, ElemType data) {
  15. if (((q->rear + 1) % MAXSIZE) == q->front) return q;
  16. q->base[q->rear] = data;
  17. q->rear = (q->rear + 1) % MAXSIZE;
  18. return q;
  19. }
  20. QueueLink* deQueue(QueueLink* q, ElemType& data) {
  21. if (q->front == q->rear) return q;
  22. data = q->base[q->front];
  23. q->front = (q->front + 1) % MAXSIZE;
  24. return q;
  25. }
  26. int getQueueLength(QueueLink* q) {
  27. return (q->rear - q->front + MAXSIZE) % MAXSIZE;
  28. }
  29. void displayQueue(QueueLink* q) {
  30. int temp = q->front;
  31. while (temp != q->rear)
  32. {
  33. printf("%d ", q->base[temp]);
  34. temp = (temp+1) % MAXSIZE;
  35. }
  36. }

 队列的链式存储结构

  1. #include<stdio.h>
  2. #define ElemType int
  3. typedef struct QNode {
  4. ElemType data;
  5. struct QNode* next;
  6. }QLinkNode;
  7. typedef struct {
  8. QLinkNode* front;
  9. QLinkNode* rear;
  10. }LinkQueue;
  11. LinkQueue* Init(LinkQueue* lq) {
  12. lq->front = lq->rear = new QLinkNode();
  13. lq->front->next = NULL;
  14. return lq;
  15. }
  16. LinkQueue* enQueue(LinkQueue* lq, ElemType data) {
  17. QLinkNode* node = new QLinkNode();
  18. node->data = data;
  19. node->next = NULL;
  20. lq->rear->next = node;
  21. lq->rear = node;
  22. return lq;
  23. }
  24. LinkQueue* deQueue(LinkQueue* lq, ElemType& data) {
  25. if (lq->rear == lq->front) return lq;
  26. QLinkNode* node = lq->front->next;
  27. data = node->data;
  28. lq->front->next = node->next;
  29. if (lq->rear == node)
  30. lq->rear = lq->front;
  31. delete node;
  32. return lq;
  33. }
  34. void display(LinkQueue* lq) {
  35. QLinkNode* p = lq->front->next;
  36. while (p!=NULL)
  37. {
  38. printf("%d ", p->data);
  39. p = p->next;
  40. }
  41. }
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/代码探险家/article/detail/918120
推荐阅读
相关标签
  

闽ICP备14008679号