zoukankan      html  css  js  c++  java
  • 用两个栈实现队列

    思路:

    假设两个栈分别为s1,s2,

    实现进队列:进队列push到s1即可

    实现出队列:首先判断s2中是否含有数据,如果有则pop即可,否则需要把s1中的数据逐个出栈,然后进入s2栈,pop s2栈即可(基本思想是一个栈负责进栈,另一个栈负责出栈)

    代码如下:

    #include<iostream>
    #include<stack>
    using namespace std;
    template<typename T> class squeue
    {
    public :
        squeue(){
        }
        ~squeue(){}
        void append(const T& node);
        T deletedata();
    private:
        stack<T> stack1;
        stack<T> stack2;
    };
    //实现进队列
    template<typename T>
    void squeue<T>::append(const T& node)
    {
        stack1.push(node);
    }
    //实现出队列
    template<typename T>
    T squeue<T>::deletedata()
    {
        if(stack2.size()<=0)//首先判断s2是否含有数据
        {
            while (stack1.size()>0)
            {
                T &temp=stack1.top();
                stack1.pop();
                stack2.push(temp);
            }
    
        }
        if(stack2.size()==0)
            throw exception("队列已满!");
        T &t=stack2.top();
        stack2.pop();
        return t;
    }
    int main()
    {
        squeue<int> s;
        s.append(1);
        s.append(2);
        s.append(3);
        s.append(4);
        cout<<s.deletedata()<<endl;
        cout<<s.deletedata()<<endl;
        cout<<s.deletedata()<<endl;
        cout<<s.deletedata()<<endl;
        return 0;
    }

    测试结果:

  • 相关阅读:
    5. Longest Palindromic Substring
    24. Swap Nodes in Pairs
    23. Merge k Sorted Lists
    22. Generate Parentheses
    21. Merge Two Sorted Lists
    20. Valid Parentheses
    19. Remove Nth Node From End of List
    18. 4Sum
    17. Letter Combinations of a Phone Number
    14. Longest Common Prefix
  • 原文地址:https://www.cnblogs.com/runninglzw/p/4486097.html
Copyright © 2011-2022 走看看