zoukankan      html  css  js  c++  java
  • 剑指offer系列——5.用两个栈实现队列/一个队列实现栈

    Q:用两个栈来实现一个队列,完成队列的Push和Pop操作。 队列中的元素为int类型。
    T:
    入队:将元素进栈A
    出队:判断栈B是否为空,如果为空,则将栈A中所有元素pop,并push进栈B,栈B出栈;如果不为空,栈B直接出栈。


    A:

        void push(int node) {
            stack1.push(node);
        }
    
        int pop() {
            int temp, temp1, temp2;
            while (!stack1.empty()) {
                temp = stack1.top();
                stack1.pop();
                stack2.push(temp);
            }
            if (stack2.empty()) {
                return -1;
            } else {
                temp1 = stack2.top();
                stack2.pop();
                while (!stack2.empty()) {
                    temp2 = stack2.top();
                    stack2.pop();
                    stack1.push(temp2);
                }
                return temp1;
            }
        }
    
    private:
        stack<int> stack1;
        stack<int> stack2;
    

    Q:用队列实现栈
    T:
    解决⽅法简单粗暴,每次压入时都把队列前⾯的都取出来再加⼊队尾:

    class MyStack {
    
        Queue<Integer> queue;
        
        /** Initialize your data structure here. */
        public MyStack() {
            queue = new LinkedList<>();
        }
        
        /** Push element x onto stack. */
        public void push(int x) {
            queue.add(x);
            for(int i = 1; i < queue.size(); i++)
                queue.add(queue.remove());
        }
        
        /** Removes the element on top of the stack and returns that element. */
        public int pop() {
            return queue.poll();
        }
        
        /** Get the top element. */
        public int top() {
            return queue.peek();
        }
        
        /** Returns whether the stack is empty. */
        public boolean empty() {
            return queue.size() == 0;
        }
    }
    
    /**
     * Your MyStack object will be instantiated and called as such:
     * MyStack obj = new MyStack();
     * obj.push(x);
     * int param_2 = obj.pop();
     * int param_3 = obj.top();
     * boolean param_4 = obj.empty();
     */
    
    
  • 相关阅读:
    2017-2018-2 20155206 《网络对抗技术》 实验六:信息搜集与漏洞扫描
    20155206 Exp5 MSF基础应用
    20155206 实验4 恶意代码分析
    20155206《网络攻防》第三次实验_免杀及其原理
    20155206 Exp2 后门原理与实践
    20155206赵飞 Exp1PC平台逆向破解及Bof基础实践
    J-19 集合对象
    J-18 集合对象
    J-17 集合对象
    J-16 集合对象
  • 原文地址:https://www.cnblogs.com/xym4869/p/12238916.html
Copyright © 2011-2022 走看看