栈--链栈

1.链栈的定义

  和链表的定义相似。

typedef struct Linknode{
	int data;  //数据域
	struct Linknode *next;  //指针域
}*LinStack;

2.初始化

bool InitStack(LinStack &S)
{
	S = (Linknode*)malloc(sizeof(Linknode));
	if (S == NULL)
		return false;
	S->next = NULL;   //链栈的下一个结点为空
	return true;
}

3.进栈

  栈的特点,后进先出(Last In First Out)
  思想:链表的头插法和栈的特点类似,例如插入数据顺序为1,2,3,4,5。在栈中的存储顺序为5,4,3,2,1。符合栈的特点。

bool Push(LinStack &S,int e)
{
	//e为进栈的元素
	Linknode* p = (Linknode*)malloc(sizeof(Linknode));
	p->data = e;
	p->next = S->next;
	S->next= p;
	return true;
}

4.出栈

bool Pop(LinStack& S)
{
	if (S->next == NULL)
		return false;   //空栈
	Linknode* p = S->next;
	S->next = p->next;
	cout << "出栈元素:" << p->data<<endl;
	free(p);
	return true;
}

5.打印全部元素

//打印全部元素
void PrintStack(LinStack S)
{
	S = S->next;
	while (S != NULL)
	{
		cout << S->data << " ";
		S = S->next;
	}
}

6.源代码

#include<iostream>
using namespace std;

//链栈定义
typedef struct Linknode{
	int data;  //数据域
	struct Linknode *next;  //指针域
}*LinStack;

//初始化
bool InitStack(LinStack &S)
{
	S = (Linknode*)malloc(sizeof(Linknode));
	if (S == NULL)
		return false;
	S->next = NULL;
	return true;
}

//头插法
bool Push(LinStack &S,int e)
{
	Linknode* p = (Linknode*)malloc(sizeof(Linknode));
	p->data = e;
	p->next = S->next;
	S->next= p;
	return true;
}

//出栈
bool Pop(LinStack& S)
{
	if (S->next == NULL)
		return false;   //空栈
	Linknode* p = S->next;
	S->next = p->next;
	cout << "出栈元素:" << p->data<<endl;
	free(p);
	return true;
}

//打印全部元素
void PrintStack(LinStack S)
{
	S = S->next;
	while (S != NULL)
	{
		cout << S->data << " ";
		S = S->next;
	}
}
int main()
{
	LinStack S;
	
	//初始化
	InitStack(S);

	//头插法
	int e = 0;
	cout << "输入你要插入的数据:";
	cin >> e;
	while (e != 9999)
	{
		Push(S, e);
		cout << "输入你要插入的数据:";
		cin >> e;
	}

	//出栈
	Pop(S);
	
	//打印全部元素
	PrintStack(S);
	return 0;
}

在这里插入图片描述

有帮助的话,点一个关注哟!

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

君生我老

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

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

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

打赏作者

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

抵扣说明:

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

余额充值