数据结构之队列

队列

队列是一种很有用的线性结构,操作系统中进程的管理,数据库系统的实现几乎都离不开队列

下面通过一个例子来看一下队列吧


实现一个链队列,输入任意的一串字符,以@作为结束的标志,然后将队列的元素逐一取出,打印在屏幕上

  1. 首先要调用函数初始化一个队列
  2. 然后通过EnQueue()函数将输入的字符顺序插入队列之中,直到输入字符@为止
  3. 通过DeQueue()函数将队列的元素输出,并且打印出来,最终队列的头指针和尾指针都指向头结点

#include "stdio.h"
typedef char ElemType;
typedef struct QNode{
    ElemType data;
    struct QNode *next;
}QNode,*QueuePtr;
typedef struct{
    QueuePtr front;  //队头
    QueuePtr rear;   //队尾
}LinkQueue;


initQueue(LinkQueue* q)
{
    /*初始化一个空队列*/
    q->front=q->rear=(QueuePtr)malloc(sizeof(QNode));
    if(!q->front) exit(0);
    q->front->next=NULL;

}

EnQueue(LinkQueue *q,ElemType e){
     QueuePtr p;
     p=(QueuePtr)malloc(sizeof(QNode)); //创建一个队列元素结点
     if(!q->front) exit(0); //创建头结点失败
     P->data=e;
     p->next=NULL;
     q->rear->next=p;
     q->rear=p;
}


DeQueue(LinkQueue *q,ElemType *e){
    //如果队列q不为空,删除q的队头元素,用e返回她的值
    QueuePtr p;
    if(q->front==q->rear) return;  //队列为空,就返回*

    p=q->front->next;
    *e=p->data;
    q->front->next=p->next;
    if(q->rear==p) q->rear=q->front;//如果队头就是队尾,就修改队尾指针
    free(p);
}


DestroyQueue(LinkQueue *q){
    while(q->front){
        q->rear=q->front->next;
        free(q->front);
        q->front=q->rear;
    }
}

int main(){
    ElemType e;
    LinkQueue q;
    initQueue(&q);
    printf("Please input a string into a queue\n");
    scanf("%c",&e);
    while(e!='@'){
        EnQueue(&q,e);
        scanf("%c",&e);
    }
    printf("The string into the queue is \n");
    while(q.front!=q.rear){
        DeQueue(&q,&e);
        printf("%c\t",e);
    }

    printf("\n");
    DestroyQueue(&q);
    getche();
}


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值