Stack的实现

来源:互联网 发布:apache 禁止目录 编辑:程序博客网 时间:2024/06/01 23:10

由于栈是一种表,因此任何实现表的方法都能实现栈。显然list和vector都支持栈的操作。

栈的链表实现

栈的第一种实现是单链表。我们通过在表的前端插入来实施push操作,通过删除表前端元素实施pop操作。top操作只是考查表前端的元素并返回它的值。有时也把pop操作和top操作合二为一。

栈的数组实现

栈的另一种实现避免了链而且可能是更流行的解决方案。它用到来自vectorbackpush_back、和pop_back,因此实现起来很简单。与每个栈相关联的是theArraytopOfStack,对于空栈它是-1(这就是空栈初始化的做法)。为将某个元素x推入栈中,我们使topOfStack增1然后置theArray[topOfStack]=x。为了弹出栈元素,我们置返回值为theArray[topOfStack],然后使topOfStack减1。

下面给出栈的链表实现:

#ifndef STACK_H#define STACK_Htemplate <typename Object>class SList{private:    struct Node{        Object data;        Node *next;                 //  单链表        Node( const Object & d = Object{ }, Node *n = nullptr )                : data(d), next(n) {  }        Node ( Object && d, Node *n = nullptr ) : data(d), next(n) {  }    };    int theSize;    Node *head;    Node *tail;public:    void init( )    {        theSize = 0;        head = new Node;        tail = new Node;        head->next = tail;    }    void clear()    {        while (theSize>0) {            pop_front();        }    }    Object front()    {        return head->next->data;    }    Object pop_front( )    {        Node *p = head->next;        Object retVal = p->data;        head->next = p->next;        delete p;        --theSize;        return retVal;    }    void push_front(const Object &x)    {        Node *p = head->next;        head->next = new Node(x, p);        ++theSize;    }    int size( )    {        return theSize;    }    SList( )   { init( ); }    SList( const SList& rhs )    {        init();        for(auto x:rhs)            push_back(x);    }    ~SList()    {        clear();    }};template <typename Object>class Stack{private:    SList<Object> SLst;public:    Stack( ) : SLst() { }    ~Stack( ) { }    bool empty( )    {        return  SLst.size() == 0;    }    int size( )    {        return SLst.size();    }    void clear( )    {        SLst.clear();    }    void push( const Object &x )    {        SLst.push_front(x);    }    Object pop( )    {        return SLst.pop_front();    }    Object top( )    {        if(SLst.size() == 0)        {            std::cout<<"栈为空!"<<std::endl;            return -1;        }        else            return SLst.front();    }};#endif // STACK_H
#include <iostream>#include "stack.h"using namespace std;int main(int argc, char *argv[]){    Stack<int> s;    for(int i=0; i<10; i++)    {        s.push(i);    }    int num = s.size();    for(int i=0; i<num/2; ++i)    {        cout<<s.pop()<<"\t";    }    cout<<endl<<s.size()<<endl;    int num2 = s.size();    for(int i=0; i<num2; ++i)    {        cout<<s.pop()<<"\t";    }    cout<<endl;    cout<<s.top();    return 0;}
原创粉丝点击