链式队列模板

本文介绍了使用C语言实现一个简单的队列数据结构,包括初始化队列、判断队列是否为空以及进行入队和出队操作的函数。
摘要由CSDN通过智能技术生成
#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<stdlib.h>
#include<stdbool.h>

typedef int datatype;

typedef struct list
{
	datatype data;
	struct list* next;
}list;

typedef struct queue
{
	list* front;
	list* rear;
}queue;

void initqueue(queue* q)
{
	q->front = q->rear = (list*)malloc(sizeof(list));
	if (q->front == NULL)
	{
		printf("error\n");
		return;
	}
	q->front->next = NULL;
}

bool isempty(queue* q)
{
	if (q->front == q->rear || q->front->next == NULL)
	{
		return true;
	}
	return false;
}

void enqueue(queue* q)
{
	printf("请输入元素的值\n");
	datatype element;
	scanf("%d", &element);
	list* newnode = (list*)malloc(sizeof(list));
	if (newnode == NULL)
	{
		printf("error\n");
		return;
	}
	newnode->data = element;
	newnode->next = NULL;
	q->rear->next = newnode;
	q->rear = newnode;
}

datatype outqueue(queue* q)
{
	if (isempty(q))
	{
		printf("empty\n");
		exit(1);
	}
	datatype temp;
	list* pointer;
	pointer = q->front->next;
	temp = pointer->data;
	q->front = pointer;
	if (pointer == q->rear)
	{
		q->rear = q->front;
	}
	return temp;
}

int main()
{
	queue q;
	initqueue(&q);
	bool flag = isempty(&q);
	if (!flag)
	{
		printf("error\n");
		return -1;
	}
	printf("有几个元素要入队\n");
	int n;
	scanf("%d", &n);
	int i = 0;
	for (i = 0; i < n; i++)
	{
		enqueue(&q);
	}
	for (i = 0; i < n; i++)
	{
		printf("%d ", outqueue(&q));
	}
	return 0;
}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值