说明
题目
【225】用队列实现栈
使用队列实现栈的下列操作:
push(x) – 元素 x 入栈
pop() – 移除栈顶元素
top() – 获取栈顶元素
empty() – 返回栈是否为空
MyStack {
private Queue<Integer> queue;
/** Initialize your data structure here. */
public MyStack() {
queue = new LinkedList<>();
}
/** Push element x onto stack. */
public void push(int x) {
queue.add(x);
int cnt = queue.size();
while (cnt-- >1){
queue.add(queue.poll()); //根据栈的特性,对队列进行处理
}
}
/** Removes the element on top of the stack and returns that element. */
public int pop() {
return queue.remove();
}
/** Get the top element. */
public int top() {
return queue.peek();
}
/** Returns whether the stack is empty. */
public boolean empty() {
return queue.isEmpty();
}
}
【232】用栈实现队列
栈的顺序为后进先出,而队列的顺序为先进先出。使用两个栈实现队列,一个元素需要经过两个栈才能出队列,在经过第一个栈时元素顺序被反转,经过第二个栈时再次被反转,此时就是先进先出顺序。
public class MyQueue {
private Stack<Integer> in = new Stack<>();
private Stack<Integer> out = new Stack<>();
/** Push element x to the back of queue. */
public void push(int x) {
in.push(x);
}
private void in2out(){
if(out.isEmpty()){
while (!in.isEmpty()){
out.push(in.pop());
}
}
}
/** Removes the element from in front of queue and returns that element. */
public int pop() {
in2out();
return out.pop();
}
/** Get the front element. */
public int peek() {
in2out();
return out.peek();
}
/** Returns whether the queue is empty. */
public boolean empty() {
return in.isEmpty()&&out.isEmpty();
}
【155】最小值栈
需要维护两个栈,一个专门用于存放最小值,当入栈时,需要将当前最小值入栈,这是为了防止,在出栈时,之前的最小值弹出,就需要同时将minStack里的最小值也弹出,此时minStack栈顶元素为之前的最小值,然后将min值更新即可。
public class MinStack {
private Stack<Integer> dataStack;
private Stack<Integer> minStack;
private int min;
/** initialize your data structure here. */
public MinStack() {
dataStack= new Stack<>();
minStack= new Stack<>();
min = Integer.MAX_VALUE;
}
public void push(int x) {
dataStack.add(x);
min = Math.min(x, min);
minStack.add(min);
}
public void pop() {
dataStack.pop();
minStack.pop();
min = minStack.isEmpty()?Integer.MAX_VALUE:minStack.peek();
}
public int top() {
return dataStack.peek();
}
public int getMin() {
return minStack.peek();
}