剑指05.用两个栈实现队列

题目描述

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

思路

栈的特点是“先进后出”,队列是“先进先出”。
每次插入元素,压入stack1。当stack2为空时,把stack1中的元素逐个弹出并压入stack2。由于先进入队列的元素被压到stack1的底端,经过弹出和压入之后就处于stack2的顶端。当stack2不为空时,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.empty()&&stack2.empty())
            throw new RuntimeException("Queue is empty.");
        if(stack2.empty()){
            while(!stack1.empty()){
                stack2.push(stack1.pop());
            }
        }
        return stack2.pop();
    }
}

 

posted @ 2020-08-05 09:53  不学无墅_NKer  阅读(114)  评论(0编辑  收藏  举报