#include <iostream>
#include <stdio.h>
#include <malloc.h>
#include "head.h"
using namespace std;
#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;
}
#ifndef LIST_H_INCLUDED
#define LIST_H_INCLUDED
#define MaxSize 5
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
#include <stdio.h>
#include <malloc.h>
#include "head.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;
}
运行结果:
知识点总结:
这是队列和数组的一种结合
学习心得:
理解代码时要细心