队列数组学习(不使用malloc)

在下这厢有礼了

平台: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





评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值