155. Min Stack
class MinStack {
int min = Integer.MAX_VALUE;
Stack<Integer> stack = new Stack<Integer>();
/** initialize your data structure here. */
public MinStack() { } public void push(int x) {
if(x <= min){
stack.push(min);
min = x;
}
stack.push(x);
} public void pop() {
if(stack.pop() == min) min = stack.pop();
} public int top() {
return stack.peek();
} public int getMin() {
return min;
}
}
232. Implement Queue using Stacks
用一个input和outlput栈,当pop时,output为空,则把input全部压入output中。
class MyQueue {
Stack<Integer> input = new Stack();
Stack<Integer> output = new Stack();
/** Initialize your data structure here. */
public MyQueue() { } /** 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();
}
}
225. Implement Stack using Queues
在push的时候就直接把顺序缓过来
class MyStack {
Queue<Integer> queue;
/** Initialize your data structure here. */
public MyStack() {
this.queue = new LinkedList<Integer>();
} /** Push element x onto stack. */
public void push(int x) {
queue.add(x);
for(int i = 0; i < queue.size() - 1; i++){
queue.add(queue.poll());
}
} /** Removes the element on top of the stack and returns that element. */
public int pop() {
return queue.poll();
} /** Get the top element. */
public int top() {
return queue.peek();
} /** Returns whether the stack is empty. */
public boolean empty() {
return queue.isEmpty();
}
}