在下这厢有礼了
平台:linux gcc编译
描述:队列数组,不使用malloc分配空间,通过数组分配空间去做队列描述。
结果如图:
queue.h文件:
定义结构体和队列
#ifndef ZWQUEUE_H_INCLUDED
#define ZWQUEUE_H_INCLUDED
#define bool int
#define false 0
#define true 1
#define N 10
#define ELemType int
typedef struct qnode {
ELemType data;
struct qnode *next;
} QNode;
typedef struct ZwQueue_p {
QNode *front;
QNode *rear;
} ZwQueue;
ZwQueue *qu[N];
QNode qn[N];
ZwQueue *InitQueue(ZwQueue *q);
bool QueueEmpty(ZwQueue *q);
int QueueLength(ZwQueue *q);
void EnQueue(ZwQueue *q, ELemType e);
bool DeQueue(ZwQueue *q);
#endif
queue.c文件:
主要是实现函数的基本操作。
#include <stdio.h>
#include <stdlib.h>
#include "queue.h"
static int index = 0;
ZwQueue *InitQueue(ZwQueue *q)
{
q->front = q->rear = NULL;
return q;
}
bool QueueEmpty(ZwQueue *q)
{
return (q->rear == NULL);
}
int QueueLength(ZwQueue *q)
{
int n = 0;
QNode *p = q->front;
while(p != NULL)
{
n++;
p = p->next;
}
return n;
}
void EnQueue(ZwQueue *q, ELemType e)
{
QNode *p = &(qn[index++]);
p->data = e;
p->next = NULL;
if(q->rear == NULL)//队列为空
q->front = q->rear = p;//队列首 等于 尾结点都为p
else
{
q->rear->next = p;//将*p节点链接到队尾,并将rear指向它(尾指法)
q->rear = p;
}
}
bool DeQueue(ZwQueue *q)
{
QNode *p;
ELemType a;
if(q->rear == NULL)//队列为空
return false;
p = q->front;
if(q->front == q->rear)//首尾指向一个节点
q->front = q->rear = NULL;
else
q->fron = q->front->next;//多个节点
a = p->data;
return a;
}
int main()
{
int i, a;
ZwQueue temp[N];
/*************************************/
/** 初始化 **/
/*************************************/
for(i = 0; i < N; ++i)
{
qu[i] = &temp[i];
qu[i] = InitQueue(qu[i]);
}
printf("请输入若干正整数:以0结束:");
scanf("%d",&a);
/*************************************/
/** 入队列 **/
/*************************************/
while(a)
{
EnQueue(qu[a%10], a);
scanf("%d",a);
}
//for(i = 0; i < N; ++i)
//printf("第%d队列:有%d个元素\n", i, QueueLength(qu[i]));
/*************************************/
/** 出队列 **/
/*************************************/
printf("按个位数整理到队列中去,显示结果:\n");
for(i = 0; i < N; ++i)
{
printf("qu[%d]:", i);
while(!QueueEmpty(qu[i]))
{
a = DeQueue(qu[i]);
printf("%d", a);
}
printf("\n");
}
return 0;
}
操作:
gcc queue.c -o queue
./queue