package leecode;
import java.util.Stack;
/**
* 两个栈实现队列
* @CreateDate 2021/4/20
*
* 请你仅使用两个栈实现先入先出队列。队列应当支持一般队列支持的所有操作(push、pop、peek、empty):
*/
public class StackToQueue {
//标志位 1代表数据在s1,且是正序 2代表数据在s2,且是反序
Integer flag = 1;
Stack<Integer> s1 = new Stack();
Stack<Integer> s2 = new Stack();
public StackToQueue(){
}
/** Push element x to the back of queue. */
public void push(int x) {
if(flag == 2){
while(s2.size() > 0){
s1.push(s2.pop());
}
flag = 1;
}
s1.push(x);
}
/** Removes the element from in front of queue and returns that element. */
public int pop() {
int r1 = peek();
int result = s2.pop();
return result;
}
/** Get the front element. */
public int peek() {
if(flag == 1){
while(s1.size() > 0){
s2.push(s1.pop());
}
flag = 2;
}
return s2.peek();
}
/** Returns whether the queue is empty. */
public boolean empty() {
return flag == 1 ? s1.size() == 0 : s2.size() == 0;
}
public static void main(String[] args) {
StackToQueue stackToQueue = new StackToQueue();
stackToQueue.push(1);
stackToQueue.push(2);
System.out.println(stackToQueue.peek());
System.out.println( stackToQueue.pop());
System.out.println(stackToQueue.empty());
}
}