day9:栈与队列part1
今天栈与队列基础
简单的互相实现,拿纸画一下模拟过程即可
232.用栈实现队列
class MyQueue {
Stack<Integer> in, out;
public MyQueue() {
in = new Stack<>();
out = new Stack<>();
}
private void inToOut() {
if (out.isEmpty())
while (!in.isEmpty())
out.push(in.pop());
}
public void push(int x) {
in.push(x);
}
public int pop() {
inToOut();
return out.pop();
}
public int peek() {
inToOut();
return out.peek();
}
public boolean empty() {
return in.isEmpty() && out.isEmpty();
}
}
/**
* 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.用队列实现栈
class MyStack {
Queue<Integer> queue;
public MyStack() {
queue = new LinkedList<>();
}
public void push(int x) {
int n = queue.size();
queue.offer(x);
while (n-- > 0) queue.offer(queue.poll());
}
public int pop() {
return queue.poll();
}
public int top() {
return queue.peek();
}
public boolean empty() {
return queue.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();
*/