参考资料:https://www.cnblogs.com/peformer/p/8029130.html
Stack.h
#pragma once
template<typename T>
class Stack
{
public:
virtual ~Stack() {};
virtual bool empty() const = 0;
virtual int size() const = 0;
virtual T &top() = 0;
virtual void pop() = 0;
virtual void push(const T &element) = 0;
};
arrStack.h
#pragma once
#include "Stack.h"
#include <iostream>
#include <algorithm>
template<typename T>
class arryStack :public Stack<T>
{
public:
arryStack(int initLenth = 20);
~arryStack();
bool empty() const;
int size() const;
T &top();
void pop();
void push(const T &element);
protected:
void ChangeLength(T* &element, int oldLenth, int newlenth);
T* stack;
private:
int stackTop;
int stackSize;
};
template<typename T>
void arryStack<T>::ChangeLength(T* &element, int oldLenth, int newlenth)
{
if (newlenth < 0)
{
std::cout << "length error";
}
T *tmp = new T[newlenth];
int minux = std::min(oldLenth,newlenth);
std::copy(element, element + minux, tmp);
delete[] element;
element = tmp;
}
//压栈
template<typename T>
void arryStack<T>::push(const T &element)
{
if (stackTop == stackSize - 1)
{
ChangeLength(stack, stackSize, stackSize * 2);
stackSize *= 2;
}
stack[++stackTop] = element;
}
//弹栈
template<typename T>
void arryStack<T>::pop()
{
if (-1 == stackTop)
std::cout << "stack empty";
stack[stackTop--].~T();
}
//获取栈顶元素
template<typename T>
T & arryStack<T>::top()
{
if (-1 == stackTop)
std::cout << "stack empty";
return stack[stackTop];
}
//获取栈长度
template<typename T>
int arryStack<T>::size() const
{
return stackSize + 1;
}
//判断栈是否为空
template<typename T>
bool arryStack<T>::empty() const
{
return stackTop == -1;
}
template<typename T>
arryStack<T>::~arryStack()
{
delete[] stack;
}
template<typename T>
arryStack<T>::arryStack(int initLenth /*= 20*/)
{
if (0 >= initLenth)
{
std::cout << "error!!!";
}
stackTop = -1;
stackSize = initLenth;
stack = new T[initLenth];
}
以下是调用示例:
int _arryList[12] = {1,18,5,2,16,22,3,8,4,6,27,9};
arryStack<int> arrSta(12);
for (int i = 0;i < 12; i++)
{
arrSta.push(_arryList[i]);
}
while (!arrSta.empty())
{
std::cout << arrSta.top();
arrSta.pop();
}