熟悉栈和队列的方法;熟悉栈和队列的数据结构,不涉及算法
232.用栈实现队列
import java.util.Stack;
class MyQueue {
//负责进栈的
Stack<Integer> stackIn;
//负责出栈的
Stack<Integer> stackOut;
public MyQueue() {
stackIn = new Stack<>();
stackOut = new Stack<>();
}
public void push(int x) {
stackIn.push(x);
}
public int pop() {
if(stackOut.isEmpty()) dumpsStackIn();
return stackOut.pop();
}
public int peek() {
if(stackOut.isEmpty()) dumpsStackIn();
return stackOut.peek();
}
public boolean empty() {
return stackOut.isEmpty()&& stackIn.isEmpty();
}
public void dumpsStackIn(){
while(!stackIn.isEmpty()) stackOut.push(stackIn.pop());
}
}
225. 用队列实现栈
class MyStack {
Queue<Integer> q1;
Queue<Integer> q2;
public MyStack() {
q1 = new LinkedList();
q2 = new LinkedList();
}
public void push(int x) {
q2.offer(x);
while(!q1.isEmpty()) q2.offer(q1.poll());
Queue tmpQueue = q2;
q2 = q1;
q1 = tmpQueue;
}
public int pop() {
return q1.poll();
}
public int top() {
return q1.peek();
}
public boolean empty() {
return q1.isEmpty();
}
}