zoukankan      html  css  js  c++  java
  • 用两个栈实现队列 (剑指offer第7题)

    用两个栈来实现一个队列,完成队列的Push和Pop操作。 队列中的元素为int类型。

    栈的特点:先进后出

    队列的特点:先进先出

    push很好实现。

    pop可能有一点难度。最开始两个栈中都没有元素,所有进队列的元素都存在stack1中。因为栈是先进后出,所有最先进来的要最后出,和队列相反。所以需要借助satack2。我想起高中数学中的负负得正。将元素从stack1中弹出放到stack2中。正好第一个进队列的元素在stack2的顶部。第一个弹出。

    当Stack2中有元素后,再新进队列的元素。直接存放在stack1中,想弹出的话,就先弹stack2中的元素。(因为本来stack2中的元素也是先进来的)当stack2中没有元素后。在将stack1中的元素放到stack2中。

    import java.util.Stack;
    
    public class Solution {
        Stack<Integer> stack1 = new Stack<Integer>();
        Stack<Integer> stack2 = new Stack<Integer>();
    
        public void push(int node) {
            stack1.push(node);
        }
    
        public int pop() {
            if(stack2.empty()){
                while (!stack1.isEmpty()){
                    stack2.push(stack1.pop());
                }
            }
            return stack2.pop();
        }
    }
    苟有恒,何必三更眠五更起;最无益,莫过一日暴十日寒。
  • 相关阅读:
    大数据平台布局图
    springMvc入门Demo例子
    用photoShop不改变图片尺寸修改存储大小
    ABBYY FineReader OCR识别图片文字到word电子
    servlet+jsp实例demo
    Runtime Hosts
    Hosting the Common Language Runtime
    Programming with Application Domains
    Application Domains Overview
    Application Domains
  • 原文地址:https://www.cnblogs.com/shaer/p/10249160.html
Copyright © 2011-2022 走看看