题目来源:https://www.nowcoder.com/practice/54275ddae22f475981afa2244dd448c6?tpId=13&&tqId=11158&rp=1&ru=/ta/coding-interviews&qru=/ta/coding-interviews/question-ranking
题目描述
用两个栈来实现一个队列,完成队列的Push和Pop操作。 队列中的元素为int类型。
题解
解题思路:
用两个栈实现队列的操作,可以一个栈用于队列进队,一个栈用于队列出队。
当队列进队时,数据直接存放到stack1
当队列出队时,如果stack2为空,先将stack1数据存放到stack2,然后stack2出栈就可以实现队列的出队;如果stack2不为空,直接将stack2的数据出栈
代码实现
import java.util.Stack;
public class Solution {
// stack1用于队列进队
Stack<Integer> stack1 = new Stack<Integer>();
// stack2用于队列出队
Stack<Integer> stack2 = new Stack<Integer>();
// 队列进队
public void push(int node) {
stack1.push(node);
}
// 队列出队
public int pop() {
// 如果stack2为空,stack1元素全部压入stack2
if (stack2.isEmpty()) {
while (!stack1.isEmpty()) {
stack2.push(stack1.pop());
}
}
// stack2不为空,直接出栈
return stack2.pop();
}
}