【算法专题 - 栈】
【题目】
编写一个算法,用栈实现一个队列。
【其他限制】
无。
【图示】
【分析】
栈结构的特点是先进后出,队列结构的特点是先进先出。对于一个无序整数序列,使用两个栈,经过进栈->出栈->进栈->出栈操作,刚好可以得到原始无序整数序列,如上图所示。
【解决方案】
具体思路:初始化两个栈StackPush和StackPop,前者仅负责入栈操作,后者仅负责出栈操作。需要注意,元素从StackPush压入StackPop中存在两个条件:
a. StackPop非空时,禁止压入元素。
b. 必须一次性全部压入,否则一旦积压,最终的出栈顺序将被打乱。
【代码实现】
/*
* DESC:
* A class implements a queue using two stacks
*/
public class StackQueue {
private Stack<Integer> stackPush;
private Stack<INteger> stackPop;
public StackQueue() {
this.stackPush = new Stack<Integer>();
this.stackPop = new Stack<Integer>();
}
private void pushToStackPop() {
if (this.stackPop.IsEmpty()) {
while (!this.stackPush.IsEmpty())
this.stackPop.push(this.stackPush.pop());
}
}
// Add element to queue.
// When adding elelment to StackPush, need to judge whether it's necessary to add it to stackPop simultaneously
public void add( int element) {
this.stackPush.push(element);
pushToStackPop();
}
// Remove a element from queue
public int poll() {
if (this.StackPush.IsEmpty() && this.StackPop.IsEmpty())
throw new RuntimeException('Queue is empty.');
pushToStackPop();
return this.stackPop.pop();
}
// Get the header element of queue
public int peek() {
if (this.StackPush.IsEmpty() && this.StackPop.IsEmpty())
throw new RuntimeException('Queue is empty.');
pushToStackPop();
return this.stackPop.peek();
}
}