一、两个队列实现栈:
思路:使用一个辅助的队列(h_queue)实现,在往原队列(data)中push时,先将原队列的数据写入h_queue,然后push新数据到data的队列头部,最后再讲辅助队列的元素写入原队列:
class MyStack {
Queue<Integer> r_queue = new LinkedList<Integer>();
Queue<Integer> h_queue = new LinkedList<Integer>();
/** Initialize your data structure here. */
public MyStack() {
}
/** Push element x onto stack. */
public void push(int x) {
while(!r_queue.isEmpty()){
h_queue.add(r_queue.peek());
r_queue.poll();
}
r_queue.add(x);
while(!h_queue.isEmpty()){
r_queue.add(h_queue.peek());
h_queue.poll();
}
}
/** Removes the element on top of the stack and returns that element. */
public int pop() {
return r_queue.poll();
}
/** Get the top element. */
public int top() {
return r_queue.peek();
}
/** Returns whether the stack is empty. */
public boolean empty() {
return r_queue.isEmpty();
}
}
二、两个栈实现队列:
思路:使用一个辅助栈(h_stack),在原栈中push数据时,首先将数据写入辅助栈中,同时将push的数据压入辅助栈,最后再将辅助栈的数据重新压入原栈,就能保证新push的数据在栈低,先进后出;
class CQueue {
Deque<Integer> stack1;
Deque<Integer> stack2;
public CQueue() {
stack1 = new LinkedList<Integer>();
stack2 = new LinkedList<Integer>();
}
public void appendTail(int value) {
stack1.push(value);
}
public int deleteHead() {
// 如果第二个栈为空
if (stack2.isEmpty()) {
while (!stack1.isEmpty()) {
stack2.push(stack1.pop());
}
}
if (stack2.isEmpty()) {
return -1;
} else {
int deleteItem = stack2.pop();
return deleteItem;
}
}
}
三、实现getMin()获取当前栈中的最小值:
思路:使用一个辅助栈(min)用来记录当前栈中最小值,每次在原栈中push数据的同时,在min中,比较新压入的值和栈中当前的最小值,如果大于,则在min再次压入一次最小值,否则压入当前的新值;在pop的时候,两个栈需要同时pop;保证min中的值为当前原栈中的最小值:
class MinStack {
Stack<Integer> rel_stack = new Stack<Integer>();
Stack<Integer> min_stack = new Stack<Integer>();
/** initialize your data structure here. */
public MinStack() {
}
public void push(int x) {
rel_stack.push(x);
if(min_stack.isEmpty()||x < min_stack.peek()){
min_stack.push(x);
}else{
min_stack.push(min_stack.peek());
}
}
public void pop() {
rel_stack.pop();
min_stack.pop();
}
public int top() {
return rel_stack.peek();
}
public int getMin() {
return min_stack.peek();
}
}