面试题 03.05. 栈排序
栈排序。 编写程序,对栈进行排序使最小元素位于栈顶。最多只能使用一个其他的临时栈存放数据,但不得将元素复制到别的数据结构(如数组)中。该栈支持如下操作:push、pop、peek 和 isEmpty。当栈为空时,peek 返回 -1。
参考
class SortedStack {
private Stack<Integer> stack;
public SortedStack() {
this.stack = new Stack<>();
}
//数据栈从空开始,每次push元素时,push后的结果都可以保证最小元素位于栈顶,且保证出栈顺序递增
public void push(int val) {
// 辅助栈
Stack<Integer> temp = new Stack<>();
while(!stack.isEmpty()) {
// 待入栈元素值 > 该栈的栈顶元素,此时数据栈更小的栈顶元素进入辅助栈
if(stack.peek() < val) {
temp.push(stack.pop());
} else {
break;
}
}
stack.push(val);
while(!temp.isEmpty()) {
stack.push(temp.pop());
}
}
public void pop() {
if(stack.isEmpty()) {
return;
}
stack.pop();
}
public int peek() {
if(stack.isEmpty()) {
return -1;
}
return stack.peek();
}
public boolean isEmpty() {
return stack.isEmpty();
}
}
/**
* Your SortedStack object will be instantiated and called as such:
* SortedStack obj = new SortedStack();
* obj.push(val);
* obj.pop();
* int param_3 = obj.peek();
* boolean param_4 = obj.isEmpty();
*/