两种栈的实现--顺序栈和链表栈

来源:互联网 发布:jar包日志 linux 输出 编辑:程序博客网 时间:2024/06/07 22:24

一、定义:栈是限定尽在一端插入或删除操作的线性表。“后进先出(LIFO)”。

二、习惯上称栈的可访问元素为站栈顶(top)元素,元素插入栈称为入栈(push),删除元素称为出栈(pop)。

三、栈的ADT:

template <typename E>class Stack{

public:

         Stack(){}        //构造函数

         virtual~Stack();  //析构函数

 

         virtual void clear() = 0;   //清空

         virtual void push() = 0;    //入栈函数

         virtual E pop() = 0;        //出栈函数

         virtual const E& topVlaue() const = 0;  //栈顶元素

         virtual int length() const = 0;         //栈的长度

};

四、顺序栈:

l  顺序栈在建立栈的时候必须说明一个固定长度。

l  当栈中有n个元素时把位置n-1作为栈顶,Top位置不存放值。

l  实现如下:

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 isempty!");

                return listArray[--top];

       }

       const E& topVlaue()const

       {

                assert(top != 0, "Stack isempty!");

                return listArray[top - 1];

       }

       int length() const { return top; }

};

五、链式栈:

l  Top是指向链式栈第一个结点(栈顶)的指针。

l  链式栈的实现:

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++;

         }

         void pop()

         {

                   assert(top!= 0, "Stack is empty!");

                   E it = top->element;

                   Link<E>*temp = top->next;

                   delete top;

                   top= temp;

                   size--;

                   return it;

         }

         const E& topValue() const

         {

                   assert(top!= 0, "Stack is empty!");

                   return top->element;

         }

         int length()const

         {

                   return size;

         }

};

原创粉丝点击