用两个栈来实现队列

题目描述

用两个栈来实现一个队列,完成队列的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();
        
    
    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

友情链接更多精彩内容