用两个栈实现队列
2019-08-08 本文已影响0人
G_uest
题目来源:牛客网--用两个栈实现队列
题目描述
用两个栈来实现一个队列,完成队列的Push和Pop操作。 队列中的元素为int类型。
解题思路
- stack1 用于直接入队存储。
- 需要出队操作时,把stack1 中的内容逐个出栈,并入栈到stack2 中;这样stack2 (相对入队顺序)就是倒序的,stack1 也已经清空。
- 再次出队时,直接从stack2 中取,如果stack2 为空,重复 2 操作,如果stack1 也为空,说明队列中已经没有数据,返回-1。
java代码
import java.util.Stack;
public class TwoStackOneQueue {
public static void main(String[] args) {
QueueTest queue = new QueueTest();
queue.push(10);
queue.push(20);
System.out.println(queue.pop());
System.out.println(queue.pop());
queue.push(30);
queue.push(40);
System.out.println(queue.pop());
}
}
// 提交代码
class QueueTest {
Stack<Integer> stack1 = new Stack<Integer>();
Stack<Integer> stack2 = new Stack<Integer>();
// stack1 用于直接入队
public void push(int node) {
stack1.push(node);
}
// stack2 用于出队
public int pop() {
// 如果stack1 和 stack2 都为空,则队列中没有数据
if (stack1.empty() && stack2.empty()){
return -1;
}
// stack2 为空,就把stack1 中的内容倒置到stack2 中
if (stack2.empty()) {
while (!stack1.empty()) {
stack2.push(stack1.pop());
}
}
return stack2.pop();
}
}