栈为先入后出,从栈顶取出元素,插入元素:
c++实现栈:
template
class MyStack{
public:void Push(const T &item);
void Pop();
bool IsEmpty() const;
T& Top();
MyStack(int stackCapacity = 5);
~MyStack();
private:
T *stack;
int top;
int capacity;
};
template
MyStack::MyStack(int stackCapacity):capacity(stackCapacity){
if(capacity <0) throw “stack > = 0”;
stack = new T[capacity];
top = -1;
}
template
MyStack::~MyStack(){
delete [] stack;
}
template
void MyStack::Push(const T &item){
if(top == capacity -1){
addCapacity(stack,capacity,2*capacity);
capacity *= 2;
}
stack[++top] = item;
}
template
bool MyStack::IsEmpty() const{
return -1 == top;
}
template
void MyStack::Pop(){
if(IsEmpty())throw “stack is Empty”;
stack[top–].~T();
}
template
T& MyStack::Top() const{
if(IsEmpty())throw “stack is Empty”;
return stack[top];
}
template
void addCapacity(T* &stack, const int oldSize, const int newSize){
if(newSize <1) throw “stack should >0”;
T *newStack = new T[newSize];
int newCapacity = std::min(oldSize, newSize);
std::copy(stack, stack+ newCacpacity,newStack);
delete [] stack;
stack = newStack;
}