用两个栈实现队列

来源:互联网 发布:linux从文件命令变量 编辑:程序博客网 时间:2024/04/28 13:55

解题思路:
入队时,将元素压入s1。
出队时,将s1的元素逐个“倒入”(弹出并压入)s2,将s2的顶元素弹出作为出队元素,之后再将s2剩下的元素逐个“倒回”s1。

这里写图片描述

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.empty()){            stack2.push(stack1.pop());        }        int val = stack2.pop();        while(!stack2.empty()){            stack1.push(stack2.pop());        }        return val;    }}
1 0
原创粉丝点击