//头文件:
//顺序存储的栈:
template <class T>
class AStack //class stack 
{
 private:
  int size;
  T * stackArray;
  int top;
 public:
  AStack(int MaxStackSize)
  {
   size = MaxStackSize;
   stackArray = new T[MaxStackSize];
   top = -1;
  }
  ~AStack() {delete [] stackArray;}
  
  int IsEmpty(void) const {return top == -1;}
  int IsFull(void) const {return top == size -1;}
  void clear(void) {top = -1;}
  bool Push(const T& item)
  {
   if (IsFull())
   {
    cout<<"pushing into full stack"<<endl;
    return false;
   }
   stackArray[++ top] = item;
   return true;  
  }
  bool Pop(T &item)
  {
   if (IsEmpty())
   {
    cout<<"poping from an empty stack"<<endl;
    return false;
   }
   item = stackArray[++ top];
   return true;
  }
  bool Peek(T &item) const
  {
   if (IsEmpty())
   {
    cout<<"peeping from an empty stack"<<endl;
    return false;
   }
   item = stackArray[top];
   return true;
  }
  
};
//头文件:
//链式存储的栈:
#include "SLList.h"
template <class T>
class LStack
{
 private:
  SLNode<T> *top;
 public:
  LStack() {top = NULL;}
  ~LStack() {clear();}
  void clear()
  {
   SLNode <T> *temp;
   while (!IsEmpty())
   {
    temp = top->next;
    delete top;
    top = temp;
   }
  }
  bool Push(const T &item)
  {
   top = new SLNode<T> (item, top);
   return true;
  }
  
  bool Pop(T &item)
  {
   if (IsEmpty())
   {
    cout<<"poping an empty stack"<<endl;
    return false;
   }
   item = top->data;
   SLNode<T> *temp = top;
   top = top->next;
   delete temp;
   return true;
  }
  bool Pop()
  {
   if (IsEmpty())
   {
    cout<<"poping an empty stack"<<endl;
    return false;
   }
   SLNode<T> *temp = top;
   
   top = top->next;
   
   delete temp;
   return true;
  }
  bool Peek(T &item) const
  {
   if (IsEmpty())
   {
    cout<<"peeking from an empty stack "<<endl;
    return false;
   }
   item = top->data;
   return true;
  }
  int IsEmpty(void) const {return top == NULL;}
  
};
 

你可能感兴趣的:(栈)