Estructura de datos: pila secuencial c ++

#include<iostream>
#include<algorithm>
#include<vector>
using namespace std;

template<class datatype>
class StackList
{
private:
	datatype *base;//栈底指针
	datatype *top;//栈顶指针
	int maxsize;//最大容量
	int len;//栈元素个数
public:
	StackList();//不带参数的构造函数
	StackList(int n);//初始化最大容量为n的构造函数
	~StackList();//析构函数
	void push(datatype value);//入栈
	void pop();//出栈
	datatype gettop();//获取栈顶元素
	datatype getbase();//获取栈底元素
	bool isequal(const StackList & A);//判断两个栈是否相等
	friend ostream &operator<<(ostream &output, const StackList &D)
	{
		if (D.len == 0)
		{
			cout << "stack is empty" << endl;
		}
		else
		{
			datatype *p = D.base;
			for (int i = 0; i < D.len; i++)
			{
				output << *p << " ";
				p++;
			}
			cout << endl;
		}
		return output;
	}
};

//不带参数的构造函数
template<class datatype>
StackList<datatype>::StackList()
{
	len = 0;
	maxsize = 10;
	base = new datatype[maxsize];
	if (!base)
		cerr << "存储分配失败" << endl;
	top = base;
}

//初始化最大容量为n的构造函数
template<class datatype>
StackList<datatype>::StackList(int n)
{
	len = 0;
	maxsize = n;
	base = new datatype[maxsize];
	if (!base)
		cerr << "存储分配失败" << endl;
	top = base;
}

//析构函数
template<class datatype>
StackList<datatype>::~StackList()
{
	delete base;
}

//入栈
template<class datatype>
void StackList<datatype>::push(datatype value)
{
	if (top - base == maxsize)
		cerr << "存储空间已满" << endl;
	else
	{
		*top++ = value;
		len++;
	}
}

//出栈
template<class datatype>
void StackList<datatype>::pop()
{
	if (base == top)
		cerr << "stack is empty ,can't pop" << endl;
	else
	{
		top--;
		len--;
	}
}

//获取栈顶元素
template<class datatype>
datatype StackList<datatype>::gettop()
{
	return *(top - 1);
}

//获取栈底元素
template<class datatype>
datatype StackList<datatype>::getbase()
{
	return *base;
}

//判断两个栈是否相等
template<class datatype>
bool StackList<datatype>::isequal(const StackList & A)
{
	if (len != A.len)
		return false;
	else
	{
		datatype *q = base;
		datatype *k = A.base;
		for (int i = 0; i < len; i++)
		{
			if (*q != *k)
				return false;
			else
			{
				q++;
				k++;
			}
		}
		return true;
	}
}

int main()
{
	//测试
	StackList<int> A;
	StackList<int> B(5);
	A.push(1);
	A.push(2);
	cout << A;
	A.pop();
	A.push(3);
	cout << A;
	cout << A.gettop() << endl;
	cout << A.getbase() << endl;
	cout << A.isequal(B) << endl;
	system("pause");
	return 0;
}

Supongo que te gusta

Origin blog.csdn.net/weixin_39139505/article/details/90320205
Recomendado
Clasificación