数据结构之队列

一 链式队列

数据结构:两个指向节点的指针front, rear;

                当链队为空时,front和rear都指向头节点,因此出队时,删除队尾节点时要注意!

link_queue.h

  1 typedef int type_t;
  2 typedef enum {false, true} bool;
  3 
  4 struct queue_node {
  5     type_t data;
  6     struct queue_node *next;
  7 };
  8 
  9 struct link_queue {
 10     struct queue_node *front;
 11     struct queue_node *rear;
 12 };
 13 
 14 struct link_queue *queue_create();
 15 bool enqueue(struct link_queue *q, type_t data);
 16 type_t dequeue(struct link_queue *q);
 17 bool queue_is_empty(struct link_queue *q);
 18 void queue_destroy(struct link_queue *q);
link_queue.c

#include <stdio.h>
  2 #include <stdlib.h>
  3 #include "link_queue.h"
  4 
  5 struct link_queue *queue_create()
  6 {
  7     struct link_queue *tmp;
  8     struct  queue_node *head;
  9 
 10     tmp = malloc(sizeof(*tmp));
 11 
 12     head = malloc(sizeof(*head));
 13 
 14     head->next = NULL;
 15 
 16     tmp->front = head;
 17     tmp->rear = head;
 18 
 19     return tmp;
 20 }
 21 
 22 bool queue_is_empty(struct link_queue *q)
 23 {
 24     return q->front == q->rear;
 25 }
 26 
 27 bool enqueue(struct link_queue *q, type_t data)
 28 {
 29     struct queue_node *tmp;
 30 
 31     tmp = malloc(sizeof(*tmp));
 32 
 33     tmp->data = data;
 34     tmp->next = NULL;
 35     q->rear->next = tmp;
 36     q->rear = tmp;
 37 }
 38 
39 type_t dequeue(struct link_queue *q)
 40 {
 41     type_t tmp;
 42     struct queue_node *node;
 43 
 44     if (queue_is_empty(q))
 45         return 0;
 46     tmp = q->front->next->data;
 47     node = q->front->next;
 48 
 49     if (q->front->next == q->rear) //防止把尾指针删掉,链式队列尾指针是指向最后一个节点,而不是最后一个节点的下一个,假设删掉最后一个节点,则q    ->rear = NULL;而此时队列为空,front和rear都应指向head!
 50         q->rear = q->front;
 51 
 52     q->front->next = node->next;
 53 
 54     free(node);
 55 
 56     return tmp;
 57 }
 58 
 59 void queue_destroy(struct link_queue *q)
 60 {
 61     struct queue_node *tmp = q->front->next;
 62 
 63     while (tmp) {
 64         struct queue_node *node = tmp;
 65         tmp = tmp->next;
 66         free(node);
 67     }
 68     free(q);
 69 }
 70 
 71 int main()
 72 {
 73     struct link_queue *tmp;
 74     int i;
 75 
 76     tmp = queue_create();
77 
 78     for (i = 1; i <= 10; i++)
 79         enqueue(tmp, i);
 80 
 81     while (!queue_is_empty(tmp))
 82         printf("%d", dequeue(tmp));
 83 
 84     printf("\n");
 85 
 86     return 0;
 87 }

注:链表与链队列的区别是什么?

从代码上看:写链表时仅定义节点就可,然后把节点串联起来!

而写链队时,先定义节点(这样能串成链表),再定义front,rear(这才是队列,这种数据结构)

如果是链栈,先定义节点(这样能串成链表),再定义stack栈顶指针(这才是栈,这种数据结构)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值