美文网首页
用两个栈来实现队列

用两个栈来实现队列

作者: 霍运浩 | 来源:发表于2019-04-16 16:28 被阅读0次

题目描述

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

解题思路

1,元素进栈放入栈A

2,元素出栈

  • 如果栈B有元素,则直接栈B出栈。
  • 如果栈A有元素,则将栈A的元素全部出栈,并且元素进入栈B,然后栈B出栈。

代码实现

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("stack is all empty!");
        }
        if(stack2.isEmpty()){
            
            while(!stack1.isEmpty()){
                stack2.push(stack1.pop());
            }
        }
        return stack2.pop();
        
    
    }
}

相关文章

网友评论

      本文标题:用两个栈来实现队列

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