两个栈实现队列
采用两个栈,一个push栈,一个pop栈,每次只有当push的时候直接进push栈,每次pop的时候,只要只从pop栈中弹出,在pop栈为null的时候,将push栈中的所有元素压栈到pop栈中,这样就还原了元素添加的顺序,先进先出,注意,只有在pop栈为null的时候才能压栈,如果不是会乱序,不会达到先进先出的目的。举例:
- push栈添加1,2,3,4,5。
- 现在需要进行pop操作,那么在保证pop栈为null的情况下将pop栈中的所有元素弹出添加到pop栈,弹出顺序为5,4,3,2,1,那么pop栈添加元素的顺序也为5,4,3,2,1,接着直接将栈顶元素1弹出,符合先进先出。
class TwoStackQueue {
private Stack<Integer> pushStack;
private Stack<Integer> popStack;
TwoStackQueue() {
pushStack = new Stack<>();
popStack = new Stack<>();
}
public void push(int num) {
pushStack.push(num);
}
public int pop() {
if (pushStack.isEmpty() && popStack.isEmpty()) {
throw new RuntimeException("Queue is empty!");
}
// 如果popStack为空,那么就将pushStack中的元素全部压入到popStack
if (popStack.isEmpty()) {
while ( !pushStack.isEmpty() ) {
popStack.push(pushStack.pop());
}
}
// 返回popStack的栈顶元素
return popStack.pop();
}
public int peek(){
if (pushStack.isEmpty() && popStack.isEmpty()) {
throw new RuntimeException("Queue is empty!");
}
if (popStack.isEmpty()) {
while ( !pushStack.isEmpty() ) {
popStack.push(pushStack.pop());
}
}
return popStack.peek();
}
}
两个队列实现栈
采用两个栈,一个queue,一个help,每次push的时候直接进queue队列,在pop的时候,直接将queue中的元素poll()到只剩一个元素,将剩下的一个元素poll()掉就行,而剩下的元素都add到help队列中,注意,每次pop或者peek后必须将两个队列的索引交换。举例:
- push了1,2,3,4,5到queue
- pop操作:队列queue依次弹出再添加到help队列,1,2,3,4 现在help元素为1,2,3,4,接着讲queue中剩下唯一一个元素5弹出,符合后进先出。
- swap()交换queue和help索引,这样有新的元素来就可以继续添加。
class TwoQueueStack {
private Queue<Integer> queue;
private Queue<Integer> help;
TwoQueueStack(){
queue = new LinkedList<>();
help = new LinkedList<>();
}
public void push(int num) {
queue.add(num);
}
public int pop(){
if (queue.isEmpty()) {
throw new RuntimeException("Stack is empty!");
}
while ( queue.size() > 1 ) {
help.add(queue.poll());
}
int res = queue.poll();
swap();
return res;
}
public int peek(){
if (queue.isEmpty()) {
throw new RuntimeException("Stack is empty!");
}
while ( queue.size() > 1 ) {
help.add(queue.poll());
}
int res = queue.poll();
help.add(res);
swap();
return res;
}
private void swap() {
Queue<Integer> tmp = help;
help = queue;
queue = tmp;
}
}