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