C++实现栈

(原创,引用请声明)
本人目前还在读大学,若对代码有疑问,评论即可,我会一一回复,若有不足,还请大佬指正。

#pragma once
#ifndef SEQSTACK_H
#define SEQSTACK_H
#include <iostream>
#include <exception>
using namespace std;
void OverflowInfo();
void UnderflowInfo();


template<class T>
class SeqStatic  //顺序栈
{
private:
	T* base; //栈基地址
	int size; //存放元素的数量
	int capcity; //容量
public:
	explicit SeqStatic(int initsize = 100); //构造函数
	virtual ~SeqStatic(); //析构函数
	SeqStatic<T>& Push(T x); //入栈操作
	SeqStatic<T>& Pop(); //出栈操作
	T GetTop() const; //得到栈顶元素操作
	bool StaticEmpty() const;//判断栈空操作
	const T* StackTopPointer() const; //获取栈顶指针操作(左值)
	void StaticShow() const; //显示栈元素操作
	friend void OverflowInfo(); //Overflow信息
	friend void UnderflowInfo(); //Underflow信息
};

template<class T> inline
SeqStatic<T>::SeqStatic(int initsize) //构造函数
	:size(0), capcity(initsize)
{
	base = new T[initsize];
}
template<class T> inline SeqStatic<T>& 
SeqStatic<T>::Push(T x) //入栈操作
{
	if (size >= capcity) OverflowInfo();
    base[size] = x;
	size++; 
	return *this;
}
template<class T> inline SeqStatic<T>& 
SeqStatic<T>::Pop() //出栈操作
{
	if (size == 0) UnderflowInfo();
	size--;
	return *this;
}
template<class T> inline T 
SeqStatic<T>::GetTop() const //得到栈顶元素操作
{
	if (size > 0) return *(base + size - 1);
	UnderflowInfo();
}
template<class T> inline bool //判断栈空操作
SeqStatic<T>::StaticEmpty() const
{
	if (size == 0) return true;
	return false;
}
template<class T> inline const T*  //得到栈顶元素操作
SeqStatic<T>::StackTopPointer() const
{
	if (size >= 0) return base + size - 1;
	UnderflowInfo();
}
template<class T> inline void 
SeqStatic<T>::StaticShow() const //显示栈元素操作
{
	if (size)
	{
		cout << "SeqStatic中的元素:" << endl;
		for (int i = 0; i < size; i++)
		{
			cout << base[i] << " ";
		}
	}
	cout << '\n';
}
template<class T> inline 
SeqStatic<T>::~SeqStatic() //析构函数
{
	delete[] base;
	size = 0;
	capcity = 0;
}
inline void OverflowInfo() //显示错误信息
{
	cout << "error行号:" << __LINE__ <<" ";
	throw overflow_error("overflow!");
}
inline void UnderflowInfo()
{
	cout << "error行号:" << __LINE__ << " ";
	throw underflow_error("underflow_error");
}

#endif // !SEQSTACK_H
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值