225. Implement Stack using Queues
栈是先进后出,队列是先进先出,要使用队列实现栈,应该在每次添加元素的时候,将队列整个颠倒,使得删除元素时满足栈的结构。
class MyStack {
private Queue<Integer>q;
/** Initialize your data structure here. */
public MyStack() {
q = new LinkedList<Integer>();
}
/** Push element x onto stack. */
public void push(int x) {
q.add(x);
for(int i = 1; i < q.size(); i ++) {
//rotate the queue to make the tail be the head
q.add(q.poll());
}
}
/** Removes the element on top of the stack and returns that element. */
public int pop() {
return q.poll();
}
/** Get the top element. */
public int top() {
return q.peek();
}
/** Returns whether the stack is empty. */
public boolean empty() {
return q.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();
*/
232. Implement Queue using Stacks
使用栈实现队列,需要两个栈,互相进行元素的颠倒
class MyQueue {
Stack<Integer> input;
Stack<Integer> output;
/** Initialize your data structure here. */
public MyQueue() {
input = new Stack();
output = new Stack();
}
/** Push element x to the back of queue. */
public void push(int x) {
input.push(x);
}
/** Removes the element from in front of queue and returns that element. */
public int pop() {
peek();
return output.pop();
}
/** Get the front element. */
public int peek() {
if (output.empty())
while (!input.empty())
output.push(input.pop());
return output.peek();
}
/** Returns whether the queue is empty. */
public boolean empty() {
return input.empty() && output.empty();
}
}
/**
* 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();
*/