一、概念
  栈是限定仅在表尾进行插入或删除操作的线性表。表尾端称为栈顶,表头端成为栈底,栈的一大特点是先进后出
二、顺序栈的实现
  和线性表一样,栈也有两种存储方式,这里实现顺序栈。
1.栈结构

typedef struct{
	SElemType *base;
	SElemType *top;
	int        stacksize;
}

2.具体实现
(1)栈空:s.top == s.base;
(2)栈满:s.top - s.base = stacksize;
(3)入栈和出栈规则:入栈时,赋值后top指针才上移,栈顶指针始终在栈顶元素的下一个位置上;出栈时,指针下移后在取值。

//头文件
#pragma once
#include<stdio.h>
#include<stdlib.h>
#define STACK_INIT_SIZE 100
#define STACKINCREASEMENT 10
typedef int SElemType;
typedef struct{
	SElemType *base;
	SElemType *top;
	int       stackSize;
}SqStack;

bool initStack(SqStack &s);

bool destoryStack(SqStack &s);

bool clearStack(SqStack &s);

bool stackEmpty(SqStack s);

int stackLength(SqStack s);

bool getTop(SqStack s,SElemType &e);

bool push(SqStack &s,SElemType e);

bool pop(SqStack &s,SElemType &e);

bool stackTraverse(SqStack s);
//cpp文件
#include"stack.h"

bool initStack(SqStack &s){

	s.base = (SElemType*)malloc(STACK_INIT_SIZE * sizeof(SElemType));
	if(!s.base) return false;

	s.top = s.base;
	s.stackSize = STACK_INIT_SIZE;
	return true;
}

bool destoryStack(SqStack &s){

	if(!s.base) return false;
	s.stackSize = 0;
	free(s.base);
	s.top = s.base = NULL;
	return true;
}

bool clearStack(SqStack &s){
	if(s.base == s.top) return false;
	s.top = s.base;
	return true;
}

bool stackEmpty(SqStack s){
	if(s.base == s.top)
		return true;
	return false;
}

int stackLength(SqStack s){
	
	return s.top - s.base;
}

bool getTop(SqStack s,SElemType &e){

	if(s.base == s.top){
		e =  0 ;
		return false;
	}
	e = *(s.top - 1);
	return true;
}

bool push(SqStack &s,SElemType e){

	if((s.top - s.base) >= s.stackSize){
		s.base = (SElemType*)realloc(s.base,(s.stackSize + STACKINCREASEMENT) * sizeof(SElemType));
		if(!s.base) return false;
		s.top = s.base + s.stackSize; 
		s.stackSize = s.stackSize + STACKINCREASEMENT;
	}

	*s.top++ = e;//先入栈,再上移动,

	return true;
}

bool pop(SqStack &s,SElemType &e){

	if(s.base == s.top) return false;
	e = *(--s.top);//先向下移动,在出栈
	return true;
}

bool stackTraverse(SqStack s){
	if(s.top == s.base) return false;

	SElemType *p = s.top - 1;
	while((p - s.base) >= 0){
		printf("%d ",*p);
		p--;
	}
	return true;
}

int main(){
	SqStack s;
	initStack(s);
	push(s,1);
	push(s,2);
	push(s,3);

	stackTraverse(s);
	printf("\n");
	printf("length = %d\n",stackLength(s));

	SElemType e ;
	getTop(s,e);
	printf("top = %d\n",e);

	pop(s,e);
	stackTraverse(s);
	printf("\n");

	getchar();
	return 0;
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值