队列

  马上要准备复试了,没事看看数据结构和算法。正好Dream-here哥们需要学c语言了,我开始写点东西,也希望我这样的低手也能对像他一样的初学小白有所帮助。前几天自己没事实现一个huffman编码和解码,其中需要统计词频高低,我当时是做了一个有序链表插入排序,其实stl中现成的priority_queue就可以完成而且效率很高,可以参考侯捷的《stl源码剖析》。昨天复习了一下图的深度和广度优先遍历,广度遍历中又需要一个队列(循环队列更好),当时是手工实现了一个最简单的。既然是入门篇,我就先从挥之不去的队列说起。

  队列是什么?

  说简单一点其实就是一堆数据,数据放在一起穿成一个线性的逻辑造型(注意这里指逻辑上是这样组织的就可以),我们都称为“线性表”。我们要说的就是一个线性表,为什么要给它取个名字叫队列呢?主要是因为我们对这个线性表中的数据的操作有规定,即“先进先出”,对数据的操作遵从“先来后到”,这不就是一个数据永远先后有序操作的理想世界了嘛,名字非常形象。

  我这里就写一个队列示例

  1 #include <malloc.h>
  2 #include <assert.h>
  3 
  4 #define NULL 0
  5 
  6 typedef struct Node
  7 {
  8     int data;
  9     struct Node *next;
 10 }queue, *queuePtr;
 11 
 12 typedef struct
 13 {
 14     queuePtr front;  //对头指针
 15     queuePtr rear;     //队尾指针
 16 }linkQueue;
 17 
 18 bool initQueue(linkQueue *Q)
 19 {
 20     Q->front = Q->rear = (queuePtr)malloc(sizeof(queue));
 21     if(Q->front==NULL)
 22         return false;
 23     Q->front->next = NULL;
 24     return true;
 25 }
 26 
 27 void destroyQueue(linkQueue *Q)  //单链表结构释放指针不需要rear属性
 28 {
 29     assert(Q!=NULL);
 30     while(Q->front)
 31     {
 32         Q->rear = Q->front->next;
 33         free(Q->front);
 34         Q->front = Q->rear;
 35     }
 36 }
 37 
 38 bool queueEmpty(linkQueue *Q)
 39 {
 40     assert(Q->front!=NULL&&Q->rear!=NULL);
 41     if(Q->front==Q->rear)
 42         return true;
 43     else
 44         return false;
 45 }
 46 
 47 int queueLength(linkQueue *Q)
 48 {
 49     assert(Q->front!=NULL);
 50     queuePtr p = Q->front;
 51     int length = 0;
 52     while(p!=Q->rear)
 53     {
 54         length++;
 55         p = p->next;
 56     }
 57     return length;
 58 }
 59 
 60 bool getHead(linkQueue *Q, int *e)
 61 {
 62     assert(Q->front!=NULL);
 63     if(queueEmpty(Q))
 64         return false;
 65     else
 66     {
 67         *e = Q->front->next->data;
 68         return true;
 69     }
 70 }
 71 
 72 void queueTraverse(linkQueue *Q, void (*visit)(int))
 73 {
 74     assert(Q->front!=NULL);
 75     queuePtr p = Q->front->next;
 76     while(p)
 77     {
 78         (*visit)(p->data);
 79         p = p->next;
 80     }
 81 }
 82 
 83 bool enQueue(linkQueue *Q, int e)
 84 {
 85     queuePtr tmp = (queuePtr)malloc(sizeof(Node));
 86     if(!tmp)
 87         return false;
 88     tmp->data = e;
 89     tmp->next = NULL;
 90     Q->rear->next = tmp;
 91     Q->rear = tmp;
 92     return true;
 93 }
 94 
 95 bool deQueue(linkQueue *Q, int *e)
 96 {
 97     if(Q->front==Q->rear)
 98         return false;
 99     queuePtr tmp = Q->front->next;
100     *e = tmp->data;
101     Q->front->next = tmp->next;
102     if(Q->rear==tmp)
103         Q->rear = Q->front;
104     free(tmp);
105     return true;
106 }
原文地址:https://www.cnblogs.com/xuangong/p/2924197.html