栈.txt

来自「一些很好用的数据结构」· 文本 代码 · 共 80 行

TXT
80
字号
//?éà?ó?????±í
template <class Elem> class Link
{
public:
    Elem element;
    Link *next;
    Link(const Elem& elemval, Link *nextval=NUll)
     {element=elemval; next=nextval;}
    Link( Link *nextval=NUll)
	{ next=nextval;}
 
};
 



template <class Elem> class LStack
{
private:
    Link<Elem>* top;
    int size;
public:
    LStack()
     {top=0; size=0;}
	~LStack()
	{
		clear();
	} 
//??3y??
  void clear();
 
//?1è???
  bool push(Elem&);
//íê???¥?a??
  bool pop(Elem&);
//??μ?TOPμ??μ
 bool topValue(Elem&)const;
 int length()const;
};



//??3y??
template <class Elem>
void LStack<Elem>::clear()
{
      while(top!=0)
	  {
           Link<Elem>* temp=top;
           top=top->next;
           delete temp;
       }//while
      size=0;
}//clear
//?1è???
template <class Elem>
bool LStack<Elem>::push(Elem& item){
     top=new Link<Elem>(item,top);
      size++; return true;
   }
//è¥???¥?a??
template <class Elem>
  bool LStack<Elem>::pop(Elem& it){
    if(size==0) return false;
    it=top->element;
    Link<Elem>* ltemp=top->next;
    delete top;
     top=ltemp; size--;
     return true;
   }//pop
//??μ?TOPμ??μ
template <class Elem>
bool LStack<Elem>::topValue(Elem& it) const
{
    if(size==0) return false;
    it=top->element;
    return true; 
}
template <class Elem>
 int LStack<Elem>::length()const {return size;}

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?