【牛客网OJ题】用栈实现一个队列

    xiaoxiao2024-12-08  63

    题目描述:

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

    分析:

    入队时,将node压入stack1 中

    出队时,如果stack1不为空的话,将stack1的值弹出,压入stack2中,Stack2弹出的值为我们所需要的值

    如果stack2不为空的话,将stack2的值弹出,压入stack1中

    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() { while(!stack1.isEmpty()){ stack2.push(stack1.pop()); } int solve = stack2.pop(); while(!stack2.isEmpty()){ stack1.push(stack2.pop()); } return solve; } }

     

    最新回复(0)