[剑指offer] --6.用两个栈来实现一个队列

题目描述

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

import java.util.Stack;

public class Solution {
    Stack<Integer> stack1 = new Stack<Integer>();
    Stack<Integer> stack2 = new Stack<Integer>();
    
    public void push(int node) {
        
    }
    
    public int pop() {
    
    }
}

解题思路

public class Solution6 {
    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.isEmpty()) {
            while (!stack1.isEmpty()) {
                stack2.push(stack1.pop());
            }
        }
        return stack2.pop();
    }
}
  • 2个栈,一个存入队队列,另一个需要当弹出队列。
  • 因为队列是先进先出,栈是先进后出,所以需要将stack1的队列弹出存入stack2,保持弹出的顺序和存入顺序一样,模拟队列效果

猜你喜欢

转载自blog.csdn.net/ouzhuangzhuang/article/details/83540327