数据结构-栈

数据结构-栈 2021/8/6 17:20

顺序实现栈

#include <iostream>
using namespace std;
#define MaxSize 10
typedef int ElemType;
typedef struct  {
	ElemType data[MaxSize];
	int top;
}SqStack;
/*
* 栈的初始化
*/
bool InitStack(SqStack &s)
{
	s.top = -1;
	return true;
}
/*
* 栈判空
*/
bool StackEmpty(SqStack s)
{
	if (s.top == -1)
		return true;
	else
		return false;
}
/*
* 进栈
*/
bool push(SqStack& s, ElemType e)
{
	if (s.top == MaxSize-1)
		return false;
	s.top++;
	s.data[s.top] = e;
	return true;
}
/*
* 出栈
*/
bool pop(SqStack& s, ElemType e)
{
	if (s.top == -1)
		return false;
	e = s.data[s.top];
	s.top = s.top - 1;
	return true;
}
/*
* 读取栈顶元素
*/
bool GetTop(SqStack s, ElemType e)
{
	if (s.top == -1)
		return false;
	e = s.data[s.top];
	return true;
}
//在实际题目中,注意题中的top是指向栈顶元素还是栈顶元素后一位

1.初始化:将top指针置为-1
2.判空:查看top指针是否置为-1
3.进栈:top指针加一,然后赋值
4.出栈:将top指针指向的值弹出,top指针减一
5.读取栈顶元素:读取top指针指向的元素即可,无需移动top指针

链栈

#include <iostream>
using namespace std;
#define MaxSize 10
typedef int ElemType;

typedef struct LinkNode{
	ElemType data[MaxSize];
	struct LinkNode* next;
}*LiStack;
//进栈出栈的操作相当于在头结点后面插入删除元素

共享栈

#include <iostream>
using namespace std;
#define MaxSize 10
typedef int ElemType;
typedef struct {
	ElemType data[MaxSize];
	int top0;
	int top1;
}ShStack;
/*
* 共享栈的初始化
*/
bool InitStack(ShStack& s)
{
	s.top0 = -1;
	s.top1 = MaxSize;
	return true;
}

共享栈相当于在静态存储区域头尾各一个栈,可以有效利用储存空间,共享栈的初始化和判满操作和一般栈的不一样,共享栈初始化时分别量两个指针指向静态区域的头和尾部,判满时是两个指针所指向的位置相同

考研加油!!!

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

Handsome Wong

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

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

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

打赏作者

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

抵扣说明:

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

余额充值