栈的链式储存

栈的链式储存

这里和基本栈(代码见栈的基本操作一)做一个小小的链接,便于理解。
在这里插入图片描述
在这里插入图片描述
其实核心代码也就是这个思路

FIRST:带头节点的

#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<stdlib.h>

typedef int ElemType;
typedef struct Linknode {
	ElemType data;
	struct Linknode* next;
}*LiStack;//Linknode,*LiStack;

void InitStack(LiStack& L)
{
	L = (Linknode*)malloc(sizeof(LiStack));
	L->next = NULL;
}

bool StackEmpty(LiStack L)
{
	if (L->next == NULL)
		return true;//空栈
	else
		return false;
}

bool InsertNextNode(LiStack &L,ElemType x)//链栈进栈不用判断栈是否满了
{
	LiStack s;
	s = (Linknode*)malloc(sizeof(LiStack));
	s->data = x;
	s->next = L->next;
	L->next = s;
	return true;
}

bool DelectNextNode(LiStack& L, ElemType &x)//出栈,删除头节点后的数据;得到栈顶元素的操作一致
{
	if (StackEmpty(L))
		return false;
	x = L->next->data;
	L->next= L->next->next;//这里注意不要写成L= L->next->next
	printf("%-3d", x);
	return true;
}

void Printf(LiStack L)
{
	int x = -1;
	while (!StackEmpty(L))
	{
		DelectNextNode(L, x);
	}
}

//1 3 5 7 9 12 13 999
int main()
{
	LiStack L;
	ElemType x;
	InitStack(L);
	scanf("%d", &x);
	while (x != 999)
	{
		InsertNextNode(L, x);
		scanf("%d", &x);
	}
	Printf(L);
	return 0;
}

SECOND:不带头节点的

#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<stdlib.h>

typedef int ElemType;
typedef struct Linknode {
	ElemType data;
	struct Linknode* next;
}*LiStack;//这样写也可以:Linknode,*LiStack;

void InitStack(LiStack& L)
{
	L= NULL;
}

bool StackEmpty(LiStack L)
{
	if (L== NULL)
		return true;//空栈
	else
		return false;
}

bool InsertNextNode(LiStack& L )//链栈进栈不用判断栈是否满了
{
	ElemType x;
	LiStack s, r;
	scanf("%d", &x);
	if (x != 999)
	{
		L = (Linknode*)malloc(sizeof(LiStack));
		L->data = x;
		L->next = NULL;
		scanf("%d", &x);
		while (x != 999)
		{
			s = (Linknode*)malloc(sizeof(LiStack));
			s->data = x;
			s->next = L;
			L = s;
			scanf("%d", &x);
		}
	}
	return true;
}

bool DelectNextNode(LiStack& L, ElemType& x)//出栈,删除头节点后的数据;得到栈顶元素的操作一致
{
	if (StackEmpty(L))
		return false;
	x = L->data;
	L= L->next;//这里注意不要写成L= L->next->next
	printf("%-3d", x);
	return true;
}

void Printf(LiStack L)
{
	int x = -1;
	while (!StackEmpty(L))
	{
		DelectNextNode(L, x);
	}
}

//1 3 5 7 9 12 13 999
int main()
{
	LiStack L;
	ElemType x;
	InitStack(L);
	InsertNextNode(L);
	Printf(L);
	return 0;
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

qq_45940479

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值