《剑指Offer》-005 -用两个栈实现队列

如题 (总结要点)

  • 用两个栈实现队列
  • 栈; 先进后出
  • 队列: 先进先出
  • 两个栈, 相等于两个杯子; 把一本水倒来倒去, 取到杯子底部的元素,并且删除,再倒回去
  • 原文链接 :

借鉴学习文章列表

  • 链接1:
  • 链接2:
  • ALiBaBaJavaCodingGuideLines有话说 :

1.主题

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

2. 代码


import java.util.Stack;
/**
 * 类的详细说明
 *
 * @author SongZeShan
 * @version 1.0
 * @Date 2019/7/12 16:40
 */
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() {
        while(!stack1.empty()){
            stack2.push(stack1.pop());
        }
        int peek= stack2.peek();
        stack2.pop();
        while(!stack2.empty()){
            stack1.push(stack2.pop());
        }
        return peek;
    }
}

3.测试

/**
 * 类的详细说明 ; 测试类
 *
 * @author SongZeShan
 * @version 1.0
 * @Date 2019/7/12 16:40
 */
public class Test {
    public static void main(String[] args) {
        Solution s = new Solution();
        for(int i=0; i<10; i++){
            s.push(i);
        }
        for(int i=0; i<10; i++){
            System.out.println(s.pop());
        }
    }
}

测试结果

0
1
2
3
4
5
6
7
8
9


原文地址:https://www.cnblogs.com/zhazhaacmer/p/11177178.html