zoukankan      html  css  js  c++  java
  • 栈 的实现

     栈有 2种实现:一种使用队列,另一种使用链表。

      当栈中有n个项时,这一实现用s[0],s[1],,..s[N-1]来保存他们。下面的代码并未实现对诸如向一个满栈中压入元素(或者从一个空栈中弹出元素)这类操作的错误检测

    template<class T>
    class Stack
    {
    private:
        T *s;
        int n;
    public:
       Stack(int maxN)
       {
           s=new T[maxN];
           n=0;
       }
       int empty() const { return n==0;}
       void push(T t)
       {
           s[n++]=t;
       }
       T pop()
       {
           return s[--n];
       }
    };

     用链表实现:

    #include<iostream>
    using namespace std;
    template<class T>
    class Stack
    {
    private:
        struct node
        {
            T t;
            node *next;
            node(T x,node *t):t(x),next(t){ }
        };
        typedef node *Link;
        Link head;
    public:
        Stack( )
        {
            head=0;
        }
    
        int empty() const { return head==0;}
    
        void push(T x)
        {
            head=new node(x,head);
        }
    
        T pop()
        {
            Link t=head->next;
               T v=head->t;
             
             delete head;
             head=t;
             return v;
        }
    };
    
    int main()
    {
        Stack<int> s;
        for(int i=0;i<10;i++)
            s.push(i);
        for(int i=0;i<10;i++)
          cout<<s.pop()<<ends;
    }

    注意,链表构造时是从右向左

  • 相关阅读:
    软工实践4
    软工实践3
    软工实践1
    《暗时间》读书笔记
    关系规范化(数据库)
    关于Git的初步使用
    软件体系结构模式
    第六周编程总结
    第五周编程总结
    第四周编程总结
  • 原文地址:https://www.cnblogs.com/youxin/p/2615441.html
Copyright © 2011-2022 走看看