栈基础操作1--顺序栈的实现

//top指针指的是一个空格
#include"pch.h"
#include<iostream>
#define MaxSize 200//顺序栈最大长度
using namespace std;
typedef  int SElemType;//数据类型
typedef struct {
	SElemType *base;//栈底
	SElemType *top;//栈顶
	int stackSize;//栈最大容量
}SqStack;
//顺序栈顶留空
//1.初始化
bool InitStack(SqStack &S) {
	//空栈
	S.base = new SElemType[MaxSize];
	if (!S.base)	return false;
	S.top = S.base;
	S.stackSize = MaxSize;
	return true;
}
//2.入栈
bool Push(SqStack &S, SElemType e) {//栈顶插入e
	if (S.top - S.base == MaxSize)
		return false;//栈满
	*S.top++ = e;//top指针指的是一个空格
	return true;
}
//3.出栈
bool Pop(SqStack &S, SElemType &e) {//栈顶出栈
	if (S.top != S.base) {//栈非空
		e = *--S.top;
		return true;
	}
	else
		return false;
}
//4.取栈顶元素,不出栈
SElemType GetTop(SqStack S) {
	if (S.top != S.base) {//栈非空
		return *(--S.top);//return *(S.top - 1);
	}
	else return NULL;
}
//5.遍历栈
void GetAll(SqStack S) {
	int time = 0;
	while (S.top != S.base) {//栈非空,判空的条件
		cout << *(--S.top) << " ";
		++time;
	}
	cout << "\n栈元素数量" << time << endl;
}
int main() {
	SqStack S; SElemType e;
	if (InitStack(S))cout << "Succeed" << endl;
	else cout << "Failed" << endl;
	//入栈
	cout << "input e:\t";
	while (cin >> e) {//按"ctrl+z"结束输入
		Push(S, e);
		cout << "input e:\t";
	}
	cout << "栈顶元素为" << GetTop(S) << endl;
	cout << "栈所有元素为" << endl;
	GetAll(S);
	//出栈
	if (Pop(S, e))
		cout << "移除的元素是" << e << endl;
	else cout << "栈空" << endl;
	cout << "栈剩下所有元素为" << endl;
	GetAll(S);
	return 0;
}
发布了122 篇原创文章 · 获赞 14 · 访问量 6189

猜你喜欢

转载自blog.csdn.net/weixin_44001521/article/details/103742983