来源:互联网 发布:unicef.cn诈骗知乎 编辑:程序博客网 时间:2024/05/20 17:42

栈是啥? 栈就是只允许在表的末端进行插入或者删除的线性表。
还不懂?
上图
栈

只允许在栈顶access(访问),插、删都只能在栈顶。显而易见stack也是一种线性表。只不过是对数据的访问做出了限制,所以我们可以用实现线性表的方式实现stack,只不过改变了对外的接口。(关于线性表可以看我的线性表的内容),即表明Stack也有两种实现方式。

顺序栈

template<class T>class SeqStack{private:    T *data;    int maxSize,top;public:    SeqStack(int size):maxSize(size){data = new T[maxSize];}    ~SeqStack(){delete []data;}    bool push(T& x){ data[top++] = x;}    bool pop(T& x){ x = data[top--];}};

链式栈

template<class T>struct stackNode{    T data;    stackNode<T>* next;    stackNode(data,next=NULL):data(data),next(next){}};template<class T>class LinkStack{private:    stackNode<T>* front;public:    LinkStack(){size=0;front=NULL;}    ~LinkStack();    bool push(T& x);    bool pop(T& x)};template<class T>bool LinkStack<T>::pop(T& x){    stackNode<T>*temp = front;    x = temp->data;    front = front->next;    delete temp;    return true;}template<class T>bool LinkStack<T>::push(T& x){    front = new stackNode<T>(x,front);    return true;}template<class T>LinkStack<T>::~LinkStack<T>(){    stackNode<T>*cur;    while(front!=NULL)    {        cur = front;        front = front->next;        delete cur;    }}//如果想直接使用Stack的话,可以使用 STL 头文件<stack>里面的stack类模板。(嗯。。。关于STL里面stack的使用,我好像也写了。如果还没有我会补上去的)
0 0
原创粉丝点击