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

[剑指offer][Java]用两个栈实现队列

作者: Maxinxx | 来源:发表于2019-03-05 22:15 被阅读0次

题目

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

程序核心思想

  • 首先思考的是队列和栈的特性。队列是先进先出,栈的先进后出。
  • 题目说要用两个栈来实现,所以第一步就创建两个栈,栈1和栈2。
  • 把第一个栈的顺序当做队列的顺序。所以队列的Push动作就可以用栈1入栈来完成。
  • 队列的Pop的动作弹出的应该得是栈1最下方的元素,所以可以把栈1的元素分别出栈到栈2,然后栈2出栈一个元素,这个元素即是队列应该Pop的元素。
  • 在执行Push和Pop操作的时候,要保证元素都在相应的栈里,即执行Push操作的时候,要保证栈2元素全部出栈,Pop操作同理。

Tips

栈的使用参考我的一篇文章《从头到尾打印链表》
https://www.jianshu.com/p/d3d6161be5bc

代码

import java.util.Stack;

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

相关文章

网友评论

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

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