队列链表

队列链表

将队列以链表的形式连接起来。
队列链表的入队只能在链表的尾部,出队只能在链表的头部。
因此队列链表需要两个指针,一个指向头,一个指向尾。
通过对头尾指针的动态移动,来操作队列的入队和出队。
//节点结构体声明
typedef struct Node
{
TYPE data; //存放的数据
struct Node* next; //节点指针
}Node;

//链表构成
typedef struct QueueList
{
Node* front; //头指针
Node* rear; //尾指针
size_t cnt; //队列长度
}QueueList;

#include<stdio.h>
#include<stdlib.h>
#include<stdbool.h>
#define TYPE int

typedef struct Node
{
	TYPE data;
	struct Node* next;
}Node;

Node* create_node(TYPE data)
{
	Node* node = malloc(sizeof(Node));
	node->data = data;
	node->next = NULL;
	return node;
}

typedef struct QueueList
{
	Node* front;
	Node* rear;
	size_t cnt;
}QueueList;

//创建
QueueList* create_queue(void)
{
	QueueList* queue = malloc(sizeof(QueueList));
	queue->front = NULL;
	queue->rear = NULL;
	queue->cnt = 0;
	return queue;
}

//队空
bool empty_queue(QueueList* queue)
{
	return 0 == queue->cnt;
}

//入队
void push_queue(QueueList* queue,TYPE data)
{
	Node* node = create_node(data);
	if(0 == queue->cnt)
	{	
		queue->front = node;
		queue->rear = node;
	}
	else
	{
		queue->rear->next = node;
		queue->rear = node;
	}
	queue->cnt++;
}

//出队
bool pop_queue(QueueList* queue)
{
	if(0 == queue->cnt)
		return false;
	Node* node = queue->front;
	queue->front = queue->front->next;
	queue->cnt--;
	free(node);
	return true;
}
//队头
TYPE front_queue(QueueList* queue)
{
	return queue->front->data;
}
//队尾
TYPE rear_queue(QueueList* queue)
{
	return queue->rear->data;
}
//销毁
void destroy_queue(QueueList* queue)
{
	while(!empty_queue(queue))
		pop_queue(queue);
	free(queue);
}

int main(int argc,const char* argv[])
{
	QueueList* queue = create_queue();
	for(int i=0; i<10; i++)
	{
		push_queue(queue,rand()%100);
		printf("rear:%d\n",rear_queue(queue));
	}
	while(!empty_queue(queue))
	{
		printf("front:%d\n",front_queue(queue));
		pop_queue(queue);
	}
	destroy_queue(queue);
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值