数据结构04----C语言队列

前面三次的链接如下:
数据结构01----单链表
数据结构02----双链表
数据结构03----栈

本篇来说一下数据结构中的队列。

五、队列

队列是是一种先进先出(FIFO)的线性表,只允许在一端进行插入(入队)操作,在另一端进行删除(出队)操作。

队列中,允许入队操作的一端叫做队尾,允许出队操作的一端叫做队头。
和之前的栈一样,C语言实现分两种讲解:链队列和顺序队列。

1.链队列
在链表的基础上,按照先进先出的原则操作数据。
C语言编程思路:
①结点定义;
②链表初始化; 定义头结点,赋值给头指针、尾指针
③入队: 尾插
出队: 删除首元结点,释放堆空间
如下图:
在这里插入图片描述
上图对应的C程序如下:

#include <stdio.h>
#include <stdlib.h>

//1、定义链表节点
typedef struct Link
{
	int data;
	struct Link *next;
}link;

//2、初始化
link *init_link(void)
{
	link *head=(link *)malloc(sizeof(link));
	head->next=NULL;
	return head;
}

//3、入队,相当于尾插
void enqueue(link **head,int elem)
{
	link *node=(link *)malloc(sizeof(link));
	node->data=elem;

	link *temp=*head;
	while(temp->next!=NULL)
	{
		temp=temp->next;
	}

	node->next=NULL;
	temp->next=node;
}

//4、出队:相当于删除首元节点
link *dequeue(link *head)
{
	if (head->next==NULL)
	{
		printf("队列已空!\n");
	}
	else
	{
		link *temp=head->next;
		printf("%d\n",temp->data);
		head->next=temp->next;
		free(temp);
	}
	return head;
}

int main(int argc, char const *argv[])
{
	link *head=init_link();

	enqueue(&head,10);
	enqueue(&head,20);
	enqueue(&head,30);
	enqueue(&head,40);

	head=dequeue(head);
	head=dequeue(head);
	head=dequeue(head);
	head=dequeue(head);
	head=dequeue(head);
	
	return 0;
}

运行结果如下:
在这里插入图片描述

2.顺序队列
把申请的空间想象成环状空间。
C语言编程思路:
①定义数组,存放数组大小的宏,头尾指针并赋初值;
②入队; 先判断是否已满。
出队; 先判断是否为空。

将判断是否已满和为空两种情况区分的方法:
牺牲掉一个存储空间。即尾指针的下一个位置与头指针相遇说明满了。请仔细理解并消化下面图片和例程。

如下图:
在这里插入图片描述
对应编程实例如下:

#include <stdio.h>

void enqueue(int *a,int *tail,int elem)
{
	if (*tail==10)
	{
		printf("队列已满!\n");
	}
	else
	{
		a[(*tail)++]=elem;
	}
}

void dequeue(int *a,int *head,int *tail)
{
	if (*head==*tail)
	{
		printf("队列为空!\n");
	}
	else
	{
		printf("%d\n",a[(*head)++]);
	}
}

int main(int argc, char const *argv[])
{
	int a[10];
	int head,tail;
	head=tail=0;

	enqueue(a,&tail,10);
	enqueue(a,&tail,20);
	enqueue(a,&tail,30);
	enqueue(a,&tail,40);
	enqueue(a,&tail,50);

	dequeue(a,&head,&tail);
	dequeue(a,&head,&tail);
	dequeue(a,&head,&tail);
	dequeue(a,&head,&tail);
	dequeue(a,&head,&tail);
	dequeue(a,&head,&tail);

	enqueue(a,&tail,10);
	enqueue(a,&tail,20);
	enqueue(a,&tail,30);
	enqueue(a,&tail,40);
	enqueue(a,&tail,50);

	dequeue(a,&head,&tail);
	dequeue(a,&head,&tail);
	dequeue(a,&head,&tail);
	dequeue(a,&head,&tail);
	dequeue(a,&head,&tail);
	dequeue(a,&head,&tail);

	enqueue(a,&tail,10);
	dequeue(a,&head,&tail);
	return 0;
}

运行结果:
在这里插入图片描述

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

all of the time

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值