C语言数据结构:栈和队列

一、栈

栈是只允许在一段插入或删除的线性表。

栈顶:允许插入和输出的一端。

栈底:不允许插入和杀出的一端。

栈又被称为是允许先进后出的线性表。

1、栈的初始化

首先我们设定一个结构体为stack

typedef int datatype;
typedef struct stack
{
	datatype* list;
	int top;
	int cap;
}Stack;

在创建一个Stack指针后,我们对栈进行初始化:

void stackinit(Stack* stack)
{
	assert(stack);
	stack->list = NULL;
	stack->top = 0;
	stack->cap = 0;
}

2、入栈

在入栈前,我们需要先判断剩余空间是否足够,如果足够则直接入栈,如果不足需要先进行扩容(二倍)再入栈,如果栈为空则需要初始设定栈容量为一个定值。

void stackpush(Stack* stack, datatype data)
{
	assert(stack);
	if (stack->cap == stack->top)
	{
		stack->cap = stack->cap == 0 ? 4 : 2 * stack->cap;
		stack->list = (datatype*)realloc(stack->list, sizeof(datatype) * (stack->cap));
	}
	stack->list[stack->top] = data;
	stack->top++;

}

3、出栈

出栈直接让top--即可,无需回收。

void stackpop(Stack* stack)
{
	assert(stack);
	assert(stack->list);
	stack->top--;
}

4、栈顶数据

datatype stacktop(Stack* stack)
{
	assert(stack->list);
	return stack->list[stack->top - 1];
}

5、判空

判空只需要判断栈顶数据是否为0个

bool stackempty(Stack* stack)
{
	assert(stack);
	assert(stack->list);
	return stack->top == 0;
}

6、销毁

void destroy(Stack* stack)
{
	free(stack->list);

}

二、队列

与栈不同的是,队列是严格的先进先出。

我们先设定一个队列节点为:

typedef int datatype;
typedef struct queuenode
{
	datatype data;
	struct queuenode* next;
}QN;

为了方便寻找队首和队尾,并实时记录队列的size,我们另设置一个结构体:

typedef struct queue
{
	QN* phead;
	QN* ptail;
	int size;
}QU;

1、初始化

void QNinit(QU* queue)
{
	queue->phead = NULL;
	queue->ptail = NULL;
	queue->size = 0;
}

2、入队

入队需要额外判断队是否为空

void QNpush(QU* queue, datatype data)
{
	QN* newnode = (QN*)malloc(sizeof(QN));
	newnode->data = data;
	newnode->next = NULL;
	if (newnode == NULL)
	{
		perror("malloc error");
		return;
	}
	if (queue->phead == NULL)
	{
		queue->phead=queue->ptail = newnode;
	
	}
	else
	{
		queue->ptail->next = newnode;
		queue->ptail = newnode;
	}
	queue->size++;
}

3、出队

出队需要首先判断对内是否只有一个元素

void QNpush(QU* queue, datatype data)
{
	QN* newnode = (QN*)malloc(sizeof(QN));
	newnode->data = data;
	newnode->next = NULL;
	if (newnode == NULL)
	{
		perror("malloc error");
		return;
	}
	if (queue->phead == NULL)
	{
		queue->phead=queue->ptail = newnode;
	
	}
	else
	{
		queue->ptail->next = newnode;
		queue->ptail = newnode;
	}
	queue->size++;
}

4、队首元素和队尾元素

int QUfront(QU* queue)
{
	assert(queue);
	assert(queue->phead);
	return queue->phead->data;
}
int QUtail(QU* queue)
{
	assert(queue);
	assert(queue->phead);
	return queue->ptail->data;
}

5、判空

bool QUempty(QU* queue)
{
	assert(queue);
	return queue->size == 0;
}

6、销毁

void QUdestroy(QU* queue)
{
	QN* cur = queue->phead;
	QN* des = queue->phead;
	while (cur)
	{
		cur = cur->next;
		free(des);
		des = cur;
	}
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值