顺序栈的实现与使用

顺序栈的实现与使用

1.1 顺序栈的模板定义
#include<iostream>
using namespace std;
const int MaxSize = 2;
template<typename DataType>
class SeqLink {
private:
	DataType data[MaxSize];
	int top;
public:
	SeqLink();
	void Push(DataType x); // 入栈函数
	DataType Pop(); // 出栈函数,并返回出栈的值
	DataType GetTop(); // 获取栈顶部的元素
	int Empty(); //判断顺序栈是否为空
};
1.2 顺序栈函数的实现
template<typename DataType>
SeqLink<DataType>::SeqLink() {
	top = -1; // 初始化一个空表
}

template<typename DataType>
int SeqLink<DataType>::Empty() {
	if (top == -1) return 1; // top为-1就是空栈
	else return 0; // top不为0不是空栈
}

template<typename DataType>
void SeqLink<DataType>::Push(DataType x) {
	if (top == MaxSize - 1)throw "The Stack is full!";
	else {
		data[top + 1] = x;
		top++;
	}

}

template<typename DataType>
DataType SeqLink<DataType>::Pop() {
	if (top == -1)throw "The Stack is empty!";
	else {
		DataType temp = data[top];
		top--;
		return temp;
	}
}

template<typename DataType>
DataType SeqLink<DataType>::GetTop() {
	if (top == -1)throw "The Stack is empty!";
	else {
		return data[top];
	}
}
1.3 顺序栈的实例化测试
int main(void) {
	SeqLink<int> SeqL{};
	cout << SeqL.Empty() << endl;
	SeqL.Push(10);
	SeqL.Push(9);
	cout << SeqL.GetTop() << endl;
	cout << SeqL.Pop() << endl;
	return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值