链栈的实现

可以设置将栈的结构体设置俩个别名,一个Stack,另一个*Lstack,也可以新创建一个栈的结构体,放它的头指针和长度,也可以设置头结点或者不设置,但这里设置用途不大,读者可据喜好自行设计。

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

typedef int ElemType;
typedef struct Stack
{
	ElemType data;
	struct Stack* next;
}Stack;
typedef struct
{
	struct Stack* top;
	int cursize;
}Lstack;

void Init_stack(Lstack *pstack)
{
	assert(pstack != nullptr);
	pstack->top = nullptr;
	pstack->cursize = 0;
}
Stack* BuyNode()
{
	Stack* s = (Stack*)malloc(sizeof(Stack));
	if (nullptr == s) exit(1);
	memset(s, 0, sizeof(Stack));
	return s;
}
bool Push(Lstack* pstack, ElemType& val)
{
	assert(pstack != nullptr);
	Stack* newnode = BuyNode();
	newnode->data = val;
	newnode->next = pstack->top;
	pstack->top = newnode;
	pstack->cursize += 1;
	return true;
}
bool IsEmpty(Lstack* pstack)
{
	assert(pstack != nullptr);
	return pstack->top == nullptr;
}
bool Pop(Lstack* pstack, ElemType& e)
{
	assert(pstack != nullptr);
	if (IsEmpty(pstack)) exit(1);
	Stack* p = pstack->top;
	pstack->top = p->next;
	e = p->data;
	free(p);
	p = nullptr;
	pstack->cursize -= 1;
	return true;
}
bool GetTop(Lstack* pstack, ElemType& e)
{
	assert(pstack != nullptr);
	if (IsEmpty(pstack)) exit(1);
	e = pstack->top->data;
	return true;
}
int Get_Lenght(Lstack* pstack)
{
	assert(pstack != nullptr);
	return pstack->cursize;
}
void Print_stack(Lstack* pstack)
{
	assert(pstack != nullptr);
	Stack* p = pstack->top;
	while (p!= nullptr)
	{
		printf("%3d", p->data);
		p = p->next;
	}
	printf("\n");
}
void Destroy_stack(Lstack* pstack)
{
	assert(pstack != nullptr);
	int n = 0;
	while (pstack->top != nullptr)
	{
		Pop(pstack, n);
	}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值