7. 用两个栈实现队列

7. 用两个栈实现队列

题目描述

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

解题思路

  • 入栈:向栈1中插入
  • 出栈:判断栈2是否为空
    • 空:栈1元素全部压入栈2
    • 栈2出栈

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-pNrkex4T-1570784378627)(/images/剑指offer/7.用两个栈实现队列.png)]

//.js
var stack1 = [];
var stack2 = [];
function push(node)
{
    // write code here
    stack1.push(node);
}
function pop()
{
    // write code here
    if(stack2.length == 0){
        while(stack1.length > 0){
            stack2.push(stack1.pop());
        }
    }
    if(stack2.length >= 0){
       return stack2.pop();
    }
}
//.java
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.size() == 0) {
            while (stack1.size() > 0) {
                stack2.push(stack1.pop());
            }
        }
        return stack2.pop();
    }
}
发布了241 篇原创文章 · 获赞 14 · 访问量 5万+

猜你喜欢

转载自blog.csdn.net/qq_29150765/article/details/102504828