一、定义
队列也叫FIFO(first in first out),队列是一种常用的数据结构其特性和栈恰好相反,它是先进先出的,
关于它的两个重要操作为入队和出队,其只能在头部和尾部进行操作,而其中能在头部尾部进行入队,出
队操作的为双端队列。
二、使用
在这里我还是用链式存储结构对一般队列进行实现,并实现其主要API。
typedef int SeqType; typedef struct Node//定义数据节点 { SeqType data; struct Node *next; }Node; typedef struct Header//定义头节点 { int Length; Node *front;//队头指针 Node *rear;//队尾指针 }Header; Header *Creat_Queue()//创建队列 { Header *header = NULL; header = (Header*)malloc(sizeof(Header)); header->Length = 0; header->front = NULL; header->rear = NULL; return header; } bool Push_Queue(Header *header,Node *node)//从队尾入队 { if(header->Length == 0) { header->front = node; header->rear= node; node->next = NULL; header->Length ++; return true; } else { node->next = NULL; header->rear->next=node; header->rear = node; header->Length ++; return true; } } bool Pop_Queue(Header *header)//从队头出队 { Node *tem = NULL; if(header->Length == 0) { printf("该队列为空不能进行出队操作"); return true; } else { tem = header->front; header->front = header->front->next; free(tem); header->Length--; return true; } } bool Destory_Queue(Header *header) { Node *tem =NULL; Node *current = NULL; if(header->Length == 0) { printf("该队列没有元素,无需摧毁\n"); return true; } current = (Node *)header->front; while(current) { tem = current ; current = current->next ; free(tem); header->Length --; } return true ; } int main() { Header *header = NULL; header = Creat_Queue(); Node *a = (Node *)malloc(sizeof(Node)); a->data = 1; Node *b = (Node *)malloc(sizeof(Node)); b->data = 2; Node *c = (Node *)malloc(sizeof(Node)); c->data = 3; Push_Queue(header,a);//入队操作 printf("队头为:%d ",header->front->data); printf("队尾为:%d\n",header->rear->data); Push_Queue(header,b); printf("队头为:%d ",header->front->data); printf("队尾为:%d\n",header->rear->data); Push_Queue(header,c); printf("队头为:%d ",header->front->data); printf("队尾为:%d\n",header->rear->data); printf("队的长度为:%d",header->Length); //入队操作队头是在不变化而队尾在变化 printf("开始执行出队操作\n"); Pop_Queue(header); printf("队头为:%d ",header->front->data); printf("队尾为:%d\n",header->rear->data); printf("队的长度为:%d\n",header->Length); //出队操作队尾发生了变化而队头未变 Destory_Queue(header); printf("%d\n",header->Length); Destory_Queue(header);//已经被摧毁无需摧毁操作 }
一定注意到时队头出队,队尾入队(当然这是对单链表存储结构说的)。
欢迎各位指出不足之处