模拟pop和push:两个队列模拟栈、使用两个栈模拟队列

it2022-05-05  113

一、使用两个栈模拟队列的pop和push操作
package com.digigd.cloud.dolphin.digigd.pub.test; import java.util.Stack; public class QueuePushPop { //栈1 Stack<Integer> stack1 = new Stack<Integer>(); //栈2 Stack<Integer> stack2 = new Stack<Integer>(); /** * 模拟队列的push方法 * */ public void push(Integer num) { stack1.push(num); } /** * 模拟队列的pop方法 * */ public int pop() { Integer re = null; if (!stack2.empty()) { re = stack2.pop(); } else { if (!stack1.empty()) { while (!stack1.empty()) { re = stack1.pop(); stack2.push(re); } if (!stack2.empty()) { re = stack2.pop(); } } } return re; } }
二、两个队列模拟栈的pop和push操作
在这里插入代码片

最新回复(0)