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

用两个栈实现队列

http://www.nowcoder.com/questionTerminal/54275ddae22f475981afa2244dd448c6

解法

首先知道 栈和队列的特点
栈:先进后出
队列:先进先出
如果用栈实现的话 可以知道 每次弹出的都是栈底的元素,所以我们可以把元素都倒在另外一个栈中,然后在弹出栈底的 最后在倒回来。

运行时间:12ms 占用内存:9428KB

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 ans = stack2.pop();
        while(!stack2.empty()){
            stack1.push(stack2.pop());
        }
        return ans;
    }
}
全部评论

相关推荐

2025-12-09 16:37
西北大学 前端工程师
点赞 评论 收藏
分享
评论
1
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务