面试题7(1):用2个栈实现队列

xiaoxiao2021-02-28  142

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

解题:当push值时,不敢栈1中有值没值,压入栈1即可。

当pop值时,如果栈2中没值,栈1中有值;则要弹出的是栈1中栈底的值。则需要把栈1中的值依次弹出压入栈2中,再弹出栈2栈顶的值即是栈1栈底的值。如果栈2中有值,则直接弹出栈2栈顶的值即可。

public class Use2StackImplQueue { 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.isEmpty()) { while (!stack1.isEmpty()) { stack2.push(stack1.pop()); } } return stack2.pop(); } }

转载请注明原文地址: https://www.6miu.com/read-29340.html

最新回复(0)