美文网首页
剑指offer:用两个栈实现队列

剑指offer:用两个栈实现队列

作者: 衣介书生 | 来源:发表于2018-03-08 14:47 被阅读3次

题目分析

题目比较简单就是用两个栈来模拟一个队列。

代码

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() {
        while(!stack1.isEmpty()) {
            stack2.push(stack1.pop());
        }
        int node = stack2.pop();
        while(!stack2.isEmpty()) {
            stack1.push(stack2.pop());
        }
        return node;
    }
}

相关文章

网友评论

      本文标题:剑指offer:用两个栈实现队列

      本文链接:https://www.haomeiwen.com/subject/nkryfftx.html