【数据结构】链式栈

链式栈

一、链式栈的栈顶在哪里?链式栈结构示意图

二、链式栈的结构:

typedef struct LSNode
{
	int data;
	struct LSNode* next;
}LSNode, *PLStack;
// 链栈的节点,由于栈顶在第一个数据节点,所以不需要top指针

三、链式栈的实现

//初始化
void InitStack(PLStack ps)
{
	assert(ps != NULL);
	ps->next = NULL;
}
//往栈中入数据
bool Push(PLStack ps, int val)
{
	assert(ps != NULL);
	LSNode *p = (LSNode*)malloc(sizeof(LSNode));
	assert(p != NULL);
	p->data = val;
	p->next = ps->next;
	ps->next = p;
	return true;
}
//获取栈顶元素的值,但是不删除
bool GetTop(PLStack ps, int* rtval)
{
	assert(ps != NULL);
	if(IsEmpty(ps))
		return false;
	*rtval = ps->next->data;
	return true;
}
//获取栈顶元素的值,但是删除
bool Pop(PLStack ps, int* rtval)
{
	assert(ps != NULL);
	if(IsEmpty(ps))
		return false;
	LSNode* p = ps->next;
	*rtval = p->data;
	ps->next = p->next;
	free(p);
	return true;
}
//判空
bool IsEmpty(PLStack ps)
{
	assert(ps != NULL);
	return ps->next == NULL;
}
//获取栈中有效元素的个数
int GetLength(PLStack ps)
{
	assert(ps != NULL);
	int count = 0;
	for(LSNode *p = ps->next; p != NULL; p = p->next)
	{
		count++;
	}
	return count; 
}
//清空所有数据
void Clear(PLStack ps)
{
	Destroy(ps);
}
//销毁
void Destroy(PLStack ps)
{
	assert(ps != NULL);
	//总是删除第一个数据节点
	LSNode *p
	while(p->next != NULL)
	{
		p = p->next;
		ps->next = p->next;
		free(p);
	}
}

四、链式栈的总结

**链栈栈顶:栈顶在表头(即第一个数据节点)(时间复杂度为O(1))

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值