栈与队列的实现

本文详细介绍了栈和队列两种数据结构的初始化、销毁、插入、删除等基本操作。栈的实现包括了初始化、入栈、出栈、获取栈顶元素、判断栈是否为空和获取栈的大小。队列的实现则涵盖了初始化、入队列、出队列、获取队头和队尾元素、判断队列是否为空以及获取队列长度。这些操作对于理解和使用数据结构至关重要。

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

目录

初始化

销毁

入栈

出栈

获取栈顶元素

判断栈是否为空

栈的大小


队列

初始化

销毁

入队列

出队列

取队头

取队尾

判空

队列长度




1.初始化

//初始化
void StackInit(ST*ps)
{
	ps->a = NULL;
	ps->capacity = 0;
	ps->top = 0;
}

2.销毁

void StackDestroy(ST*ps)
{
	free(ps->a);
	ps->a = NULL;
	ps->capacity = 0;
	ps->top = 0;
}

3.入栈

void StackPush(ST*ps, SDataType x)
{
	assert(ps);
	if (ps->top == ps->capacity)
	{
		int newcapacity = ps->capacity == 0 ? 4 : ps->capacity * 2;
		SDataType*tmp = (SDataType*)realloc(ps->a, newcapacity*(sizeof(SDataType)));
		assert(tmp);
		ps->a = tmp;
		ps->capacity = newcapacity;

	}
	ps->a[ps->top] = x;
	ps->top++;
}

4.出栈

void StackPop(ST*ps)
{
	assert(ps);
	assert(!StackEmpty(ps));
	ps->top--;
}

5.判空

bool StackEmpty(ST*ps)
{
	assert(ps);
	return ps->top == 0;
}

6.栈顶元素

SDataType StackFront(ST*ps)
{
	assert(ps);
	assert(!StackEmpty(ps));
	return ps->a[ps->top - 1];
}

7.栈大小

int StackSize(ST*ps)
{
	assert(ps);
	assert(!StackEmpty(ps));
	return ps->top;
}

队列

1.初始化

void QueueInit(Queue*pq)
{
	assert(pq);
	pq->head = pq->tail = NULL;

}

2.销毁

void QueueDestroy(Queue*pq)
{
	QNode*cur = pq->head;
	while (cur)
	{
		QNode*next = cur->next;
		free(cur);
		cur = next;
	}
	pq->head = pq->tail = NULL;
}

3.入队列

void QueuePush(Queue*pq, QDataType x)
{
	assert(pq);
	QNode*newnode = (QNode*)malloc(sizeof(QNode));
	assert(newnode);
	newnode->next = NULL;
	newnode->data = x;
	if (pq->head == NULL)
	{
		pq->head = pq->tail = newnode;
	}
	else
	{
		pq->tail->next = newnode;
		pq->tail = newnode;

	}
}

4.出队列

void QueuePop(Queue*pq)
{
	assert(pq);
	assert(!QueueEmpty(pq));
	if (pq->head->next == NULL)
	{
		free(pq->head);
		pq->head = pq->tail = NULL;
	}
	else
	{
		QNode*next = pq->head->next;
		free(pq->head);
		pq->head = next;
	}

}

5.判空

bool QueueEmpty(Queue*pq)
{

	assert(pq);
	return pq->head == NULL;

}

6.获取队头

QDataType QueueTop(Queue*pq)
{
	assert(pq);
	return pq->head->data;

}

7.获取队尾

//获取队尾
QDataType QueueBack(Queue*pq)
{
	return pq->tail->data;
}

8.队列长度

//队列长度
int QueueSize(Queue*pq)
{
	QNode*cur = pq->head;
	int size = 0;
	while (cur)
	{
		size++;
		cur = cur->next;

	}
	return size;

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值