1 栈、队列和堆
1.1 两个队列实现栈
栈:1 2 3 4 5 出栈顺序 5 4 3 2 1, 相应的队列(先进先出)应该为 5 4 3 2 1。
通过两个队列来实现栈:
假设队列1已经有了 1 2 3 4,这是来了个5。我们让5进入队列2,然后把队列1(4,3,2,1)中的数据赋值给队列2,此时,队列2为 5 4 3 2 1。最后,我们把队列2中的数据赋值给队列1,队列1中的数据为5 4 3 2 1.
/**
* 通过临时队列来实现栈
*/
class MyStack {
Queue<Integer> dataQueue;
Queue<Integer> tempQueue;
/** Initialize your data structure here. */
public MyStack() {
dataQueue = new LinkedList<Integer>();
tempQueue = new LinkedList<Integer>();
}
/** Push element x onto stack. */
public void push(int x) {
tempQueue.add(x);
while(!dataQueue.isEmpty()){
tempQueue.offer(dataQueue.poll());
}
while(!tempQueue.isEmpty()){
dataQueue.offer(tempQueue.poll());
}
}
/** Removes the element on top of the stack and returns that element. */
public int pop() {
return dataQueue.poll();
}
/** Get the top element. */
public int top() {
return dataQueue.peek();
}
/** Returns whether the stack is empty. */
public boolean empty() {
if(dataQueue.isEmpty()){
return true;
}
return false;
}
}
1.2 两个栈实现队列
和1.1的原理类似。
class CQueue {
Stack tempStack;
Stack dataStack;
public CQueue() {
tempStack = new Stack<Integer>();
dataStack = new Stack<Integer>();
}
public void appendTail(int value) {
while(!dataStack.isEmpty()){
tempStack.push(dataStack.po