1.栈的ADT

template <typename E> class Stack {
private:
    void operator=(const Stack&){}
    stack(const Stack&){}
public:
    Stack(){}
    virtual ~Stack(){}
    virtual void clear()=0;
    virtual void push(const E& it)=0;
    virtual E pop()=0;
    virtual const E& topValue() const=0;
    virtual int length() const=0;
};
2.顺序栈类的实现

top定义为表示栈中的第一个空闲位置。空栈的top=0,即第一个空闲位置。

template <typename E> class AStack:public Stack<E>{
private:
   int maxSize;
   int top;
   E *listArray;
public:
   AStack(int size=defaultSize)
   { maxSize=size; top=0; listArray=new E[size]; }
   ~AStack() { delete [] listArray; }
   void clear() { top=0; }
   void push(const E& it){
      Assert(top!=maxSize,"Stack is full");
      listArray[top++]=it;
   }
   E pop() {
      Assert(top!=0,"Stack is empty");
      return listArray[--top];
   }
   const E& topValue() const {
      Assert(top!=0,"Stack is empty");
      return listArray[top-1];
   }
   int length() const { return top; }
};
3.链式栈

链式栈唯一的数据成员是top,它是一个指向链式栈第一个结点(栈顶)的指针。

template <typename E> class Link {
public:
   E element;
   Link *next;
   Link(const E& elemval,Link * nextval=NULL)
      { element=elemval;  next=nextval;}
   Link(Link* nextval=NULL) { next=nextval;}
};

template <typename E> class LStack:public Stack<E>{
private:
   Link<E>* top;
   int size;
public:
   LStack(int sz=defaultSize)
   {  top=NULL; size=0; }
  ~LStack() { clear(); }
  void clear() {
     while(top!=NULL){
        link<E>* temp=top;
        top=top->next;
        delete temp;
     }
     size=0;
   }
   void push(const E& it){
      top=new Link<E>(it,top);
      size++;
   }
   E pop(){
      Assert(top!=NULL,"Stack is empty");
      E it=top->element;
      Link<E>* ltemp=top->next;
      delete top;
      top=ltemp;
      size--;
      return it;
   }
   const E& topValue() const{
      Assert(top!=0,"Stack is empty");
      return top->element;
   }
   int length() const { return size; }
};


如何通过链式栈找到链中n/2处的数值:

可以用两个指针,快指针两个两个结点的走,慢指针一个一个结点的走。当快指针到达栈底时,慢指针恰好到中间。





评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值