数据结构——顺序栈的基本操作

栈的基本运算

InitStack(&S): 初始化栈S

StackEmpty(): 判断栈是否为空

Push(e): 将元素e放入栈顶

Pop(e): 移走栈顶的元素,同时由e带回该元素的值

Gettop(): 获取栈顶的元素,但不从栈中移走

#include <stdio.h>
#include <stdlib.h>
# define STACK_INIT_SIZE 100
# define STACKINCREMENT 10
typedef struct {
		int  *base;
		int  *top;
		int  stacksize;
}SqStack; 

bool InitStack(SqStack &S)
{
	S.base = (int *)malloc(STACK_INIT_SIZE*sizeof(int));
	if(!S.base)
		return false;
	S.top = S.base;
	S.stacksize = STACK_INIT_SIZE;
	return true;
}

bool Push(SqStack &S,int e){
	if(S.top-S.base==S.stacksize){
		S.base = (int *)realloc(S.base,(S.stacksize+STACKINCREMENT)*sizeof(int));
	if(!S.base)
		return false;
	S.top = S.base + S.stacksize;
	S.stacksize = S.stacksize + STACKINCREMENT;
	}
	*S.top = e;
	S.top++;
	return true;
}

bool StackEmpty(SqStack &S){
	if(S.base == S.top)
		return true;
	else
		return false;
}

int Gettop(SqStack &S){
	int *p = S.top -1;
	int e = *p;
	return e;
}

int Pop(SqStack &S){
	int e = *--S.top;
	return e;
}
int main(){
	SqStack sq;
	InitStack(sq);
	Push(sq,1);
	Push(sq,2);
	if(StackEmpty(sq))
		printf("空\n");
	else
		printf("非空\n");
	printf("栈顶元素:%d\n",Gettop(sq));
	printf("元素出栈:%d\n",Pop(sq));
	printf("元素出栈:%d\n",Pop(sq));
	if(StackEmpty(sq))
		printf("空\n");
	else
		printf("非空\n");
	return 0;
}

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

末世灯光

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

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

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

打赏作者

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

抵扣说明:

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

余额充值