栈化为队
题意是用两个栈去模拟一个队列
栈是FILO 先进后出
队列为FIFO先进先出
要保证入队的时候,另一个的元素需要先进入stack1
出队的时候,stack1的元素又要弹出压入stack2
public class T34 {
//stack1 压入 stack2 弹出
Stack<Integer> stack1;
Stack<Integer> stack2;
/** Initialize your data structure here. */
public T34() {
stack1 = new Stack<>();
stack2 = new Stack<>();
}
/** Push element x to the back of queue. */
public void push(int x) {
//stack2有数据的时候 弹出,并且将数据压入stack1
while(stack2.size() !=0){
int j= stack2.pop();
stack1.push(j);
}
//stack2没数据就直接压入 stack1
stack1.push(x);
}
/** Removes the element from in front of queue and returns that element. */
public int pop() {
//stack1有数据 就弹出,并且压入stack2
while (stack1.size()!=0){
Integer pop = stack1.pop();
stack2.push(pop);
}
//stack1没数据 就直接弹出
return stack2.pop();
}
/** Get the front element. */
public int peek() {
//stack1有数据 弹出stack1 ,压入stack2
while(stack1.size() != 0){
int x= stack1.pop();
stack2.push(x);
}
//并且返回stack2中元素
return stack2.peek();
}
/** Returns whether the queue is empty. */
public boolean empty() {
if (stack1.isEmpty() && stack2.isEmpty()){
return true;
}
return false;
}
public static void main(String[] args) {
T34 queue = new T34();
queue.push(1);
queue.push(2);
int peek = queue.peek();// 返回 1
queue.pop(); // 返回 1
int peek2 = queue.peek();// 返回 2
System.out.println(peek);
System.out.println(peek2);
queue.empty(); // 返回 false
}
}
升级版本 泛型通用对象
public class MyQueue<T> {
//一个用来 入队
Stack<T> inStack;
//一个用来 出队
Stack<T> outStack;
public MyQueue(){
inStack = new Stack<>();
outStack = new Stack<>();
}
public void push(T t){
while (outStack.size()!=0){
T pop = outStack.pop();
inStack.push(pop);
}
inStack.push(t);
}
public T pop(){
while (inStack.size()!=0){
T pop = inStack.pop();
outStack.push(pop);
}
return outStack.pop();
}
//查看最后队尾元素
public T peek(){
while(inStack.size()!=0){
T pop = inStack.pop();
outStack.push(pop);
}
return outStack.peek();
}
public Boolean isEmpty(){
if (inStack.isEmpty() && outStack.isEmpty()){
return true;
}
return false;
}
public static void main(String[] args) {
MyQueue<String> queue = new MyQueue<>();
queue.push("FU");
queue.push("Y");
String pop = queue.pop();
System.out.println(pop);
queue.peek();
String pop1 = queue.pop();
System.out.println(pop1);
}
}