【数据结构】栈的顺序存储结构

  • 后进先出表
  • 栈顶是活动的
  • 当栈顶指针为-1时为空栈
  • 栈顶指针最大值为数组定义大小 MAX_SIZE-1

宏定义

//宏定义
#define MAX_SIZE	50
#define FAILED		-1
#define SUCCESS		0
typedef char ElemType;
typedef struct SqStack
{
	ElemType data[MAX_SIZE];
	int top;
}SqStack;

typedef SqStack StackType;

基本操作

//初始化栈
StackType* InitStack()
{
	StackType* s = (StackType*)malloc(sizeof(StackType));
	s->top = -1;
}

//销毁栈
void DestroyStack(StackType* s)
{
	free(s);
}

//栈判空
int StackEmpty(StackType* s)
{
	return (s->top == -1);
}

//入栈
int Push(StackType* s, ElemType e)
{
	if (s->top == MAX_SIZE - 1) return FAILED;
	s->data[++s->top] = e;
	return SUCCESS;
}

//出栈
int Pop(StackType* s, ElemType* e)
{
	if (s->top == -1) return FAILED;
	*e = s->data[s->top--];
	return SUCCESS;

}

//得到栈顶元素
int GetTop(StackType* s, ElemType* e)
{
	if (s->top == -1) return FAILED;
	*e = s->data[s->top];
	return SUCCESS;
}

应用

//设计一种方法判断一个字符串是否为对称串
int GetTop(StackType* s, ElemType* e)
{
	if (s->top == -1) return FAILED;
	*e = s->data[s->top];
	return SUCCESS;
}

int JudgeSym(ElemType * str)
{
	if (s->top == -1) return FAILED;
	*e = s->data[s->top];
	return SUCCESS;
}

int JudgeSym(ElemType * str)
{
	StackType* s = InitStack();
	ElemType a ;
	ElemType* e=&a;
	for (int i = 0; str[i] != 0; i++)
		Push(s, str[i]);
	for (int i = 0; str[i] != 0; i++)
	{
		Pop(s, e);
		if (str[i] != (*e))
		{
			DestroyStack(s);
			return FAILED;
		}
	}
	DestroyStack(s);
	return SUCCESS;
}

共享栈

在这里插入图片描述

  • 在设计共享栈时,由于一个数组(MAX_SIZE)有两个端点,两个栈有两个栈底
  • 让一个栈的栈底为数组的始端,下标为0
  • 另一个栈底为数组的末端,即MAX_SIZE - 1
  • 共享栈的4要素
  1. 栈空:栈1空为 top1==-1 ,栈2空为top2=MAXSIZE;
  2. 栈满条件:top1==top2-1
  3. 元素进栈:进栈1操作为top1++,data[top1]=x;进栈2操作为top2–,data[top2]=x;
  4. 元素出栈:出栈1操作为data[top1]=x,top1–;出栈2操作为data[top1]=x,top1++;
typedef struct DStack
{
	ElemType data[MAX_SIZE];
	int top1,top2;
}DStack;

设计算法时要需要增加一个形参来进行表示对哪一个栈进行操作;
i=1时,栈1;
i=2时,栈2;

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值