链式队列

来源:互联网 发布:mac版枪火兄弟连2 编辑:程序博客网 时间:2024/06/08 12:20

队列:先进先出(FIFO),队列是一种特殊的线性表,特殊之处在于它只允许在表的前端(front)进行删除操作,而在表的后端(rear)进行插入操作,和栈一样,队列是一种操作受限制的线性表。进行插入操作的端称为队尾,进行删除操作的端称为队头。

这里写图片描述

#include<stdio.h>#include<stdlib.h>#include<assert.h>typedef struct Qnode{   struct Qnode *next;   int data;     }Qnode,*Queueptr;typedef struct {  Queueptr front;  Queueptr rear;}QueueLink;QueueLink *InitQueue(){     QueueLink *Q;     Qnode *p;     Q = (QueueLink*)malloc(sizeof(QueueLink));     if(NULL == Q)      return NULL;      p = (Queueptr)malloc(sizeof(Qnode));     p->next = NULL;     p->data = 0;     Q->front = Q->rear = p;                   //让队列前后指针指向同一地址      return Q;}///////////入队 QueueLink *InQueue(QueueLink *Q,int e){    assert(Q != NULL);    Qnode *p;    p = (Queueptr)malloc(sizeof(Qnode));    p->next = NULL;      p->data = e;    Q->rear->next = p;                        //使用尾插法,从尾部接入新结点     Q->rear = p;    return Q;    }///////////出队 QueueLink *outQueue(QueueLink *Q){    if(Q->front == Q->rear)     return NULL;    Qnode *p;     p = Q->front->next;               //出队列是从队头     Q->front = p;    printf("出队的元素是: %d\n",p->data);    free(p);                                 //出队后将该结点删除回收空间     return Q;}////////////打印输出队列所有元素 int printQueue(QueueLink *Q){    assert(Q != NULL);    Qnode *p,*temp;    int i = 0;     p = Q->front->next;         printf("队列中的数字是:");     while(p != NULL)    {      ++i;      printf("%d ",p->data);      p = p->next;    }    printf("\n该队列的长度是:%d\n",i);    return 1;}///////////销毁队列 void DetoryQueue(QueueLink *Q){     Qnode *p;     while(Q->front != Q->rear)      {        p = Q->front;        Q->front = Q->front->next;        free(p);     }     free(Q->front);     printf("队列已销毁\n");} int main(){    QueueLink *Q;    int i;    int a[] = {5,7,9,10,13,15};    Q = InitQueue();    for(i=0; i<6;i++)     Q = InQueue(Q,a[i]);    printQueue(Q);    outQueue(Q);    printQueue(Q);    DetoryQueue(Q);    return 0;}
1 0
原创粉丝点击