用两个栈实现队列(Java实现)

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

解题思路
两个栈stack1和stack2 。
开始时,每次添加队尾元素到stack1中。
如果需要弹出队头元素,则将stack1中的元素弹出并push到stack2中,再将stack2的栈顶元素弹出,即为弹出了队头元素。
如果stack2中是非空的,再在队尾中添加元素的时候仍然加到stack1中,从stack2中弹出队头元素。
只有当stack2为空的时候,弹出队头元素才需要将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(stack2.size() == 0) {
            while(!stack1.isEmpty()) {
                int temp = stack1.peek();
                stack2.push(temp);
                stack1.pop();
            }
        }
        int res = stack2.peek();
        stack2.pop();
        return res;
    }
}

猜你喜欢

转载自blog.csdn.net/melwx/article/details/88103754
今日推荐