队列的C语言实现

在学习队列的时候我们需要理解到底队列是什么呢?队列与堆栈不一样的,队列的先进先出,堆栈是先入后出。

一、 在我们看代码之前我们需要了解两个结构体。如下:

1-1.这个是队列元素的结构体:

typedef struct node{
	Item item;
	struct node *next;
}Node;
1-2.下面是队列的结构体,包括了队列的当前数目以及对头指针和队尾指针:

typedef struct queue{
	Node *font;
	Node *rear;
	int items;
}Queue;
二、下面是队列的实现代码:

2-1.队列初始化:

void InitQueue(Queue *pq)
{
	pq->font = pq->rear = NULL;//把队列的头指针和尾指针初始化为空,避免野指针产生
	pq->items = 0;//初始化队列当前数目
}
2-2.判断队列是否蛮:

bool QueueIsFull(const Queue *pq)
{
	return pq->items == MAXQUEUE;
}
2-3判断队列是否为空:

bool QueueIsEmpty(const Queue *pq)
{
	return pq->items == 0;
}
2-4。获取当前队列数目:

int QueueItemCount(const Queue *pq)
{
	return pq->items;
}
2-5.copy元素到队列节点中:

int QueueItemCount(const Queue *pq)
{
	return pq->items;
}
2-6.插入元素到队列中:

bool EnQueue(Item item,Queue *pq)
{
	Node *pnew;
	if(QueueIsFull(pq))//第一判断队列是否为满
		return 0;
	pnew = (Node*)malloc(sizeof(Node));//申请一个节点空间
	if(pnew == NULL){
		printf("malloc pnew fail.\n");
		exit(1);
	}
	CopyToNode(item,pnew);//复制信息到节点中
	pnew->next = NULL;//把节点中的next指针赋空
	if(QueueIsEmpty(pq)){//判断队列是否为空,为空则把此节点插入到队列头
		pq->font = pnew;
	}
	else
		pq->rear->next = pnew;//不为空的话就插入到尾结点的下一个
	pq->rear = pnew;//移动尾节点到新插入的节点处
	pq->items ++;//队列数累加
	printf("pq->items=%d\n",pq->items);
	return 1;
}
2-7.一处一个队列元素:

bool DeQueue(Item *pitem,Queue *pq)
{
	Node *pt;
	if(QueueIsEmpty(pq))//判断队列是否为空
		return 0;
	pt = pq->font;//存储头结点元素地址到临时变量中,给后面释放此节点的空间使用
	pq->font = pq->font->next;//移动头结点指针到后一位
	free(pt);//释放节点
	pq->items --;//队列元素减一
	if(pq->items == 0)
		pq->rear = NULL;
	return 1;
}
三、测试队列函数:

int main(void)
{
	Queue line;
	Item temp;
	char ch;
	InitQueue(&line);
	while((ch = getchar()) != 'q')
	{
		if((ch != 'a')&&(ch != 'd'))
			continue;
		if(ch == 'a'){
			printf("scanf temp\n");
			scanf("%d",&temp);
			if(!QueueIsFull(&line)){
				printf("will enter %d temp into line.\n",temp);
				EnQueue(temp,&line);
			}else{
				printf("the queue is full.\n");
			}
		}else if(ch == 'd'){
			if(QueueIsEmpty(&line)){
				printf("will delete temp .\n");
				DeQueue(NULL,&line);
			}else{
				printf("the queue is empty.\n");
			}
		}
	}
}
以上的代码在linux上面编译并自己测试通过了的,大家可以放心使用,虽然简单,但是队列的思路就是这样。。。





评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值