算法Leetcode数据结构和算法分析

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

2018-08-12  本文已影响2人  繁著

本文首发于我的个人博客:尾尾部落

题目描述

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

解题思路

两个栈 stack1 和 stack2:

参考代码

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(stack1.isEmpty() && stack2.isEmpty())
            throw new RuntimeException("Queue is empty!");
        int node;
        if(stack2.isEmpty()){
            while(!stack1.isEmpty()){
                node = stack1.pop();
                stack2.push(node);
            }
        }
        return stack2.pop();
        
    }
}
上一篇 下一篇

猜你喜欢

热点阅读