基本思想:使用两个栈,一个负责存入数据,另一个专门负责弹出数据
package package1128;
import java.util.Stack;
/**
* @author CHENG 2018/11/28
*/
public class MyQueue {
private Stack stackIn, stackOut;
/**初始化*/
public MyQueue() {
stackIn = new Stack();
stackOut = new Stack();
}
/**push操作*/
public void push(int x) {
stackIn.push(x);
}
/**pop操作*/
public int pop() {
/**如果stackOut为空,则转移栈中的数据*/
if(stackOut.size() == 0) {
while (!stackIn.empty()) {
int temp = (int) stackIn.pop();
stackOut.push(temp);
}
}
/**非空,直接返回数据*/
return (int) stackOut.pop();
}
/**peek操作*/
public int peek() {
if(stackOut.size() == 0) {
while (!stackIn.empty()) {
int temp = (int) stackIn.pop();
stackOut.push(temp);
}
}
return (int) stackOut.peek();
}
/**empty判断*/
public boolean empty() {
if(stackIn.size() == 0 && stackOut.size() == 0) return true;
return false;
}
/**测试*/
public static void main(String[] args) {
MyQueue queue = new MyQueue();
queue.push(2);
queue.push(3);
System.out.println(queue.pop());
System.out.println(queue.empty());
System.out.println(queue.pop());
System.out.println(queue.empty());
}
}