用两个栈实现队列

2017-09-16  本文已影响0人  SinX竟然被占用了

题目描述:
用两个栈来实现一个队列,完成队列的push和pop操作。 队列中的元素为int类型。

import java.util.Stack;
 
public class Solution {
     
    Stack<Integer> stack1 = new Stack<>();
    Stack<Integer> stack2 = new Stack<>();
     
    public void push(int node) {
         
        stack1.push(node);
    }
     
    public int pop() {
         
        if(!stack2.isEmpty()) {
            return stack2.pop();
        } else {
            //将stack1中元素全部弹入stack2中
            while(!stack1.isEmpty()) {
                stack2.push(stack1.pop());
            }
            return stack2.pop();
        }
    }
}
上一篇 下一篇

猜你喜欢

热点阅读