C/C++ 第七周栈和队列 (二)队列数组 项目四

断了今生、忘了曾经 提交于 2020-04-06 06:05:46
/*     
*Copyright(c)2017,烟台大学计算机学院     
*All right reserved.     
*文件名:main.cpp sqqueue.h sqqueue.cpp     
*作者:黄士胜    
*完成日期:2017年10月20日     
*版本号:v1.0     
*     
*问题描述:  见项目四-队列数组 
*输入描述:输入70 59 90 72 67 88 80 64 29 97 18 83 40 13 0   
*程序输出:见运行结果截图     
*/ 


主函数:

#include <stdio.h>
#include<malloc.h>
#include"../liqueue.h"
#define N 10
int main()
{
    int i,a;
    LiQueue *qu[N];//定义队列指针数组
    for(i=0;i<N;i++)
        InitQueue(qu[i]);
     //为队列中加入值
    printf("输入若干正整数,以0结束: ");
    scanf("%d", &a);
    while(a)
    {
        enQueue(qu[a%10], a);
        scanf("%d", &a);
    }

    //输出各个队列
    printf("按个位数整理到各个队列中后,各队列出队的结果是: \n");
    for(i=0;i<N;i++)
    {
        printf("qu[%d]: ",i);
        while(!QueueEmpty(qu[i]))
        {
             deQueue(qu[i], a);
            printf("%d ",a);
        }
        printf("\n");
    }
    for(i=0;i<N;i++)
        DestroyQueue(qu[i]);
    return 0;

}

liqueue.cpp代码:

#include"liqueue.h"
#include<stdio.h>
#include<malloc.h>
void InitQueue(LiQueue *&q)  //初始化链队
{
    q=(LiQueue *)malloc(sizeof(LiQueue));
    q->front=q->rear=NULL;

}
void DestroyQueue(LiQueue *&q) //销毁链队
{
    QNode *p=q->front,*r;
    if(p!=NULL)
    {
        r=p->next;
        while(r!=NULL)
        {
            free (p);
            p=r;
            r=p->next;
        }
    }
    free(p);
    free(q);
}
bool QueueEmpty(LiQueue *q)  //判断链队是否为空
{
    return(q->rear==NULL);
}
int QueueLength(LiQueue *q) //返回队列中数据元素个数
{
    int n=0;
    QNode *p=q->front;
    while(p!=NULL)
    {
        n++;
        p=p->next;

    }
    return (n);

}
void enQueue(LiQueue *&q,ElemType e) //入队
{
    QNode *p;
    p=(QNode *)malloc(sizeof (QNode));
    p->data=e;
    p->next=NULL;
    if(q->rear==NULL)
        q->front=q->rear=p;
    else
    {
        q->rear->next=p;
        q->rear=p;

    }
}
bool deQueue(LiQueue *&q,ElemType &e)   //出队
{
    QNode *t;
    if(q->rear==NULL)
        return false;
        t=q->front;
        if(q->front==q->rear)
            q->front=q->rear=NULL;
        else
            q->front=q->front->next;
        e=t->data;
        free(t);
        return true;

}
liqueue.h代码:

typedef int ElemType;
typedef struct qnode
{
    ElemType data;
    struct qnode *next;
} QNode;        //链队数据结点类型定义

typedef struct
{
    QNode *front;
    QNode *rear;
} LiQueue;          //链队类型定义
void InitQueue(LiQueue *&q);  //初始化链队
void DestroyQueue(LiQueue *&q);  //销毁链队
bool QueueEmpty(LiQueue *q);  //判断链队是否为空
int QueueLength(LiQueue *q);  //返回队列中数据元素个数
void enQueue(LiQueue *&q,ElemType e);  //入队
bool deQueue(LiQueue *&q,ElemType &e);   //出队

运行结果截图:




学习新得:

通过此项目学习到了如何运用队列数组完成对数据的入队,使用队列数组,实际上需要将十个队列的指针,顺序存储到一个数组中即可。







发布了34 篇原创文章 · 获赞 9 · 访问量 1万+
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!