第七周-队列数组

来源:互联网 发布:推荐算法常用数据集 编辑:程序博客网 时间:2024/05/16 14:52

问题描述:创建十个队列,分别编号为0-9(处理为队列数组,编号即下标)。输入若干个正整数,以数字零作为结束。设输入值为x,其个位数的大小为i,则将x插入到编号为i的队列中。最后输出所有的非空队列。

  设程序运行时输入:70 59 90 72 67 88 80 64 29 97 18 83 40 13 0

#ifndef LIQUEUE_H_INCLUDED#define LIQUEUE_H_INCLUDED#include<malloc.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);   //出队#endif // LIQUEUE_H_INCLUDED


 

#include <stdio.h>#include "head.h"#define N 10int main(){  LiQueue *qu[N];  int a,i;  for(i=0;i<N;i++)    InitQueue(qu[i]);    printf("输入若干正整数,以0结束: ");  while(1)  {      scanf("%d",&a);      enQueue(qu[a%10],a);      if(a==0)        break;  }  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;}


 

#include "head.h"#include<iostream>void InitQueue(LiQueue *&q){    q=(LiQueue *)malloc(sizeof(LiQueue));    q->front=q->rear=NULL;}void DestroyQueue(LiQueue *&q){    QNode *r,*p=q->front;    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){    return q->rear->data;}void enQueue(LiQueue *&q,ElemType e){    QNode *p;    p=(QNode *)malloc(sizeof(QNode));    p->data=e;    p->next=NULL;    if(q->rear==NULL)        q->rear=q->front=p;    else    {        q->rear->next=p;        q->rear=p;    }}bool deQueue(LiQueue *&q,ElemType &e){    QNode *t;    t=q->front;    if(q->rear==NULL)        return false;    if(q->rear==q->front)        q->rear=q->front=NULL;        else        {            q->front=q->front->next;        }    e=t->data;    free(t);    return true;}


运行结果:

 

0 0
原创粉丝点击