当前位置:   article > 正文

数据结构初阶之队列(C语言实现)_队列简单oj题 c语言

队列简单oj题 c语言

队列的定义查一下百度百科就可以,很简单,本文只谈顺序队列,不涉及循环队列。

队列(常用数据结构之一)_百度百科

文章主要目的是为了用链表的形式实现队列常用的接口函数,一般有初始化,销毁,队尾插入,删除队头,返回队头,返回队尾,判空和返回当前队列元素个数。

首先先给出队列元素的定义和整个队列的形式

  1. typedef int QDataType;
  2. typedef struct QueueNode
  3. {
  4. struct QueueNode* next;
  5. QDataType data;
  6. }QNode;
  7. typedef struct Queue
  8. {
  9. QNode* head;
  10. QNode* tail;
  11. }Queue;

初始化

  1. void QueueInit(Queue* pq)
  2. {
  3. assert(pq);
  4. pq->head = pq->tail = NULL;
  5. }

销毁

  1. void QueueDestroy(Queue* pq)
  2. {
  3. assert(pq);
  4. QNode* cur = pq->head;
  5. while (cur)
  6. {
  7. QNode* next = cur->next;
  8. free(cur);
  9. cur=next;
  10. }
  11. pq->head = pq->tail = NULL;
  12. }

队尾插入

  1. void QueuePush(Queue* pq, QDataType x)
  2. {
  3. assert(pq);
  4. QNode* newnode = (QNode*)malloc(sizeof(QNode));
  5. if (newnode == NULL)
  6. {
  7. printf("malloc fail\n");
  8. exit(-1);
  9. }
  10. newnode->data = x;
  11. newnode->next = NULL;
  12. if (pq->tail == NULL)
  13. {
  14. pq->head = pq->tail = newnode;
  15. }
  16. else
  17. {
  18. pq->tail->next = newnode;
  19. pq->tail = newnode;
  20. }
  21. }

删除队头

  1. void QueuePop(Queue* pq)
  2. {
  3. assert(pq);
  4. assert(!QueueEmpty(pq));
  5. //
  6. //
  7. if (pq->head->next == NULL)
  8. {
  9. free(pq->head);
  10. pq->head = pq->tail = NULL;
  11. }
  12. else
  13. {
  14. QNode* next = pq->head->next;
  15. free(pq->head);
  16. pq->head = next;
  17. }
  18. }

返回队头

  1. QDataType QueueFront(Queue* pq)
  2. {
  3. assert(pq);
  4. assert(!QueueEmpty(pq));
  5. return pq->head->data;
  6. }

返回队尾

  1. QDataType QueueBack(Queue* pq)
  2. {
  3. assert(pq);
  4. assert(!QueueEmpty(pq));
  5. return pq->tail->data;
  6. }

判空

  1. bool QueueEmpty(Queue* pq)
  2. {
  3. assert(pq);
  4. return pq->head == NULL;
  5. }

返回当前队列元素个数

  1. int QueueSize(Queue* pq)
  2. {
  3. assert(pq);
  4. QNode* cur = pq->head;
  5. int size = 0;
  6. while (cur)
  7. {
  8. ++size;
  9. cur = cur->next;
  10. }
  11. return size;
  12. }

队列也是相对而言比较简单的,但是这里的OJ题并不简单,准确地说使用C语言实现并不简单,接下来会更新关于栈和队列地相互实现以及循环队列的OJ题。

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

闽ICP备14008679号