数据结构(栈):顺序栈

/*
	*数据结构(栈):顺序栈
	*栈为空时,栈顶指针top==-1;栈不为空时,top==栈顶元素数组下表+1
	*top != 0; top > 0时,表示栈中元素个数;
	*Date:2017/4/14
	*/

#include <stdio.h>
#include <stdlib.h>
#define MaxSize 50
#define ElemType char

typedef struct{
	ElemType data[MaxSize];	//用静态数组模拟顺序栈
	int top;	//栈顶指针
}SqStack;

void initStack(SqStack &S);	//初始化顺序栈
ElemType getTop(SqStack S);	//取栈顶元素
void push(SqStack &S,ElemType e);	//进栈
void pop(SqStack &S,ElemType *e);	//出栈
bool emptyStack(SqStack S);	//判断栈S是否为空,若为空则返回true,否则返回false
void destroyStack(SqStack &S);	//销毁栈S

void initStack(SqStack &S){
	char ch;
	S.top = -1;	//空栈,栈顶指针==-1
	while(scanf("%c",&ch) != EOF && ch != '\n'){
		if(S.top == -1){
			S.top = 0;
		}
		S.data[S.top++] = ch;
	}

}

ElemType getTop(SqStack S){
	return S.data[S.top-1];
}

void push(SqStack &S,ElemType e){
	S.data[S.top++] = e;
}

void pop(SqStack &S,ElemType *e){
	*e = S.data[--S.top];
}

bool emptyStack(SqStack S){
	if(S.top == -1){
		return true;
	}else{
		return false;
	}
}

void destroyStack(SqStack &S){
	S.top = -1;
}

int main(){
	freopen("in.txt","r",stdin);
	SqStack S;
	ElemType e;
	initStack(S);
	printf("getTop(S):%c\n",getTop(S));
	pop(S,&e);
	printf("pop(S,&e):%c\n",e);
	printf("getTop(S):%c\n",getTop(S));
	push(S,'p');
	printf("push(S,'p'):%c\n",getTop(S));
	if(emptyStack(S)){
		printf("S is NULL\n");
	}else{
		printf("S isn't NULL\n");
	}
	destroyStack(S);
	printf("destroyStack(S):\n");
	if(emptyStack(S)){
		printf("S is NULL\n");
	}else{
		printf("S isn't NULL\n");
	}
	return 0;
}

in.txt:

orange

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值