232.用栈实现队列
简单模拟
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() {
dump();
return stackOut.pop();
}
public int peek() {
dump();
return stackOut.peek();
}
public boolean empty() {
if(stackIn.isEmpty() && stackOut.isEmpty()){
return true;
}
return false;
}
private void dump(){
if(!stackOut.isEmpty()) return;
while(!stackIn.isEmpty()){
stackOut.push(stackIn.pop());
}
}
}
/**
* Your MyQueue object will be instantiated and called as such:
* MyQueue obj = new MyQueue();
* obj.push(x);
* int param_2 = obj.pop();
* int param_3 = obj.peek();
* boolean param_4 = obj.empty();
*/
225用队列实现栈
说实在的,对java基础数据结构的接口不熟悉,需要赶紧补一下
class MyStack {
Queue<Integer> dui;
public MyStack() {
dui = new LinkedList<>();
}
public void push(int x) {
dui.offer(x);
}
public int pop() {
int len = dui.size();
len--;
while(len-->0){
dui.offer(dui.poll());
}
int res = dui.poll();
return res;
}
public int top() {
int len = dui.size();
len--;
while(len-->0){
dui.offer(dui.poll());
}
int res = dui.peek();
dui.offer(dui.poll());
return res;
}
public boolean empty() {
return dui.isEmpty();
}
}
/**
* Your MyStack object will be instantiated and called as such:
* MyStack obj = new MyStack();
* obj.push(x);
* int param_2 = obj.pop();
* int param_3 = obj.top();
* boolean param_4 = obj.empty();
*/