C++栈实现

#include<iostream>
using namespace std;

template<class T>
class Stack
{
private:
	int top;//当前栈顶位置
	T* arr;//储存元素
	int cap;//最大容量
public:
	Stack(int c=10);//默认容量
	bool empty();//是否为空栈
	T front();//返回
	T pop();//返回并从栈中移除
	void Push(T key);//压入栈
	int size();//返回元素个数
	int capacity();//返回当前最大容量
	~Stack();//析构
	void clear();//清空栈
};
template<class T>
Stack<T>::clear()
{
	delete arr;
	cap = 10;
	top = -1;
}
template<class T>
Stack<T>::~Stack()
{
	delete arr;
}
template<class T>
Stack<T>::Stack(int c)
{
	top = -1;
	cap = c;
	arr = new T[cap+1];
}
template<class T>
bool Stack<T>::empty()
{
	return top == -1;
}
template<class T>
T Stack<T>::front()
{
	if (!empty())
		return arr[top--];
	else
		throw "empty";
}
template<class T>
T Stack<T>::pop()
{
	if (!empty())
		return arr[top--];
	else
		throw "empty";
}
template<class T>
void Stack<T>::Push(T key)
{
	top++;
	if (top > cap)
	{
		T* temp = new T[2 * cap];
		for (int i = 0; i < top; i++)
			temp[i] = arr[i];
		delete arr;
		arr = temp;
		cap *= 2;
	}
	arr[top] = key;
}
template<class T>
int Stack<T>::size()
{
	return top + 1;
}
template<class T>
int Stack<T>::capacity()
{
	return cap;
}


猜你喜欢

转载自blog.csdn.net/qq_40510553/article/details/80250566