数据结构之队列的基本实现(代码)

/*基本队列的实现*/
#include<stdio.h>
#include<stdlib.h>
#include<assert.h>
#include<malloc.h>
#include<stdbool.h>

//通过链表实现就要定义一个链表
typedef struct ListNode
{
	struct ListNode* next;
	int val;
}ListNode;
//定义两个节点指针  也可以解决使用二级指针的方法
typedef struct queue
{
	ListNode* head;
	ListNode* tail;
}queue;

//接口
//初始化栈接口
void QueueInit(queue*q)
{
	q->head = q->tail = NULL;
}
//销毁栈接口
void QueueDestory(queue* q)
{
	assert(q);
	ListNode* cur = q->head;
	while (cur)
	{
		ListNode*next= cur->next;
		free(cur);
		cur = next;
	}
	q->head = q->tail = NULL;


}
//队尾进接口
void QueuePush( queue*q,int val)
{
	assert(q);
	ListNode* newnode = (ListNode*)malloc(sizeof(ListNode));
	if (newnode == NULL)
	{
		printf("创建节点失败!\n");
		exit(-1);
	}
	else
	{
		newnode->next = NULL;
		newnode->val = val;
	}

	if (q->tail==NULL)
	{
		q->tail = q->head = newnode;
	}
	else
	{
		q->tail->next = newnode;
		q->tail = newnode;
	}
}
//队头出接口
void QueuePop(queue* q)
{
	assert(q);
	assert(q->head);
	//极端情况 就是队列只有一个节点的情况  此时你的tail的空间已经被释放了但是你的tail还是指向一块地址的  所有tail会形成一个野指针 
	//单独判断
	if (q->head->next==NULL)
	{
		free(q->head);
		q->head = q->tail = NULL;
	}
	else
	{
		ListNode* tmp = q->head->next;
		free(q->head);
		q->head = tmp;
	}
	
}

bool QueueEmpty(queue* q);
//返回队头的接口
int QueueFront(queue* q)
{
	assert(q);
	if (!QueueEmpty(q))
	{
		return q->head->val;
	}
	else
	{
		return NULL;
	}
}

//返回队尾接口
int QueueBack(queue* q)
{
	assert(q);
	assert(q->head);
	return q->tail->val;
}
bool QueueEmpty(queue* q)
{
	assert(q);
	//为空就是真
	return q->head == NULL;
}

int main()
{

	queue q;
	QueueInit(&q);

	QueuePush(&q, 1);
	QueuePush(&q, 2);
	QueuePush(&q, 3);
	QueuePush(&q, 4);
	while (!QueueEmpty(&q))
	{
		printf("%d ", QueueFront(&q));
		QueuePop(&q);
	}
	printf("\n");
	int ret = QueueFront(&q);
	printf("%d ", ret);
	return 0;
}

  • 6
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值