#include"chainNode.h"
#include"exceptions.h"
#include"stack.h"
template<class T>
class linkedStack:public stack<T>
{
public:
linkedStack(int initialCapacity = 10)
{
stackTop = NULL;
stackSize = 0;
}
~linkedStack();
bool empty() const { return stackSize == 0; }
int size() const { return stackSize; }
T &top() //反回栈顶的元素
{
if (stackSize == 0)
{
throw stackEmpty();
}
return stackTop->element;
}
void pop();//删除栈顶元素
void push(const T& theElement)
{
/*chainNode<T>*currentNode = stackTop;
stackTop = new chainNode<T>();
stackTop->element = theElement;
stackTop->next = currentNode; */ //等价于
stackTop =new chainNode<T>(theElement, stackTop);
stackSize++;
}
private:
chainNode<T> *stackTop; //栈顶指针
int stackSize;//栈中元素个数
};
template<class T>
linkedStack<T>::~linkedStack()
{
while (stackTop != NULL)
{
chainNode<T> *nextNode = stackTop->next;
delete stackTop;
stackTop = nextNode;
}
}
template<class T>
void linkedStack<T>::pop()
{//删除栈顶元素
if (stackSize == 0)
{
throw stackEmpty();
}
chainNode<T> *nextNode = stackTop->next;
delete stackTop;
stackTop = nextNode;
stackSize--;
}
chainNode.h
template <class T>
struct chainNode
{
T element;
chainNode<T> *next;
chainNode<T>(T element, chainNode<T> *next)
{
this->element = element;
this->next = next;
}
};
stack.h
#ifndef stack_
#define stack_
using namespace std;
template<class T>
class stack
{
public:
virtual ~stack() {}
virtual bool empty() const = 0;
// return true iff stack is empty
virtual int size() const = 0;
// return number of elements in stack
virtual T& top() = 0;
// return reference to the top element
virtual void pop() = 0;
// remove the top element
virtual void push(const T& theElement) = 0;
// insert theElement at the top of the stack
};
#endif