顺序栈

#include 
#include 
using namespace std;

template 
void change_size(T* &a, int oldSize, int newSize)
{
	T* p = new T[newSize];

	int size = min(oldSize,newSize);

	copy(a,a+size,p);

	delete [] a;
	a = p;
}


template 
class MyStack
{
public:
	MyStack(int defaultCap = 5);
	~MyStack()
	{
		delete [] stack;
	}

	void pop();			//出栈
	void push(T & item);//入栈

	T & Top();			//获取栈顶元素
	bool isEmty();    //判断是否为空

private:
	int capacity;
	int top;
	T *stack;

};

template 
MyStack::MyStack(int defaultCap):capacity(defaultCap)
{
	top = -1; //栈顶最初的位置设置为-1

	stack = new T[capacity]; //申请大小

}

template 
void MyStack::pop()
{
	if (isEmty()) throw "stack is empty";

	stack[top].~T();
	top--;
}
template 
bool MyStack::isEmty()
{
	return top == -1;
}

template 
void MyStack::push(T &item)
{
	if (top >= capacity -1)
	{
		change_size(stack, capacity, capacity*2);
		capacity *= 2;
	}

	stack[++top] = item;
		
}

template
T& MyStack::Top()
{
	if (isEmty()) throw "stack is empty";

	return stack[top];
}


int main()
{
	MyStack  myStack(5);

	int arry[8] = {1,2,3,4,5,6,7,8};

	for (int i = 0; i < sizeof(arry) / sizeof(arry[0]); i++)
	{
		myStack.push(arry[i]);
		cout << myStack.Top() << " " ;
	}
	
	cout << endl;
	for (int i = 0; i < sizeof(arry) / sizeof(arry[0]); i++)
	{
		myStack.pop();
		cout << myStack.Top() << " ";
	}
	cout << endl;

	return 0;
}

运行结果:

顺序栈_第1张图片

你可能感兴趣的:(C++数据结构与算法)