队列

本文详细介绍了队列这一基本数据结构的实现方法,包括使用C语言进行队列的初始化、判断是否为空、入队、出队以及获取队头元素等核心操作,并通过具体代码示例展示了队列的使用过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

头文件

typedef enum{FALSE = 0, TRUE} BOOL;
typedef int Data;

typedef struct node
{
	Data data;
	struct node *next;
}Node;

typedef struct queue
{
	//Node *list;//考虑头指针空不空,头结点不用考虑
	Node *front;
	Node *rear;
}Queue;


//初始化队列
void Init(Queue *s);

//判断空队列
BOOL Empty(Queue *s);

//入队列
void Push(Queue *s, Data data);

//出队列
void Pop(Queue *s);

//获取队头元素
Data GetTop(Queue *s);


#endif

函数

#include "queue.h"
#include <stdlib.h>

//初始化队列
void Init(Queue *q)
{
	if (NULL == q)
		return;
	
	q->front = NULL;
}

//判断空队列
BOOL Empty(Queue *q)
{
	if (NULL == q)
		return FALSE;
	
	if(q->front == NULL)
		return TRUE;
	
	return FALSE;
}


//入队列
void Push(Queue *q, Data data)
{
	if (NULL == q)
		return;
	
	Node *node = (Node*)malloc(sizeof(Node)/sizeof(char)); 
	
	node->data = data;
	if(NULL == q->rear)
	{
		q->rear  = node;
		q->front = node;
	}
	else
	{
		q->rear->next  = node;
		q->rear = node;
	}
}


//出队列
void Pop(Queue *q)
{
	if (NULL == q)
		return;

	if(Empty(q) == TRUE)
		return;
	
	Node *tmp =q->front;
	q->front = tmp->next;
	free(tmp);
	
	if(NULL == q->front)
	{
		q->rear = NULL;
	}
		
}

//获取队头元素
Data GetTop(Queue *q)
{
	if (NULL == q)
		return;
	
	if (Empty(q) == TRUE)
		exit(-1);  //程序退出
	
	return q->front->data;
}

主函数

#include <stdio.h>
#include "queue.h"

int main()
{
	Queue(q);//创建队列
	
	Init(&q);//初始化队列
	
	int i;
	for (i = 0; i < 10; i++)
	{
		Push(&q, i);//入队列
	}
	
	while(!Empty(&q))
	{
		Data data = GetTop(&q);//取栈顶数据
		printf("%d  ",data);
		Pop(&q);//一个一个出栈
	}
	
	printf("\n");

	return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值