剑指offer(用两个栈来实现队列)

五、栈和队列

1. 用两个栈来实现队列

题目描述:

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

思路:

入队:stack1入栈。

出队:若stack2非空,则stack2弹出栈顶元素;若stack2为空,且stack1非空,则将stack1中的元素全部压入stack2中,然后弹出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.isEmpty() && !stack1.isEmpty()) {
            while (!stack1.isEmpty()) {
                stack2.push(stack1.pop());
            }
        }
        return stack2.pop();
    }
}
posted @ 2020-03-13 18:51  Java程序员的进阶之路  阅读(83)  评论(0编辑  收藏  举报