import java.util.Stack;
public class StackSort {
}
class SortedStack {
Stack<Integer> data = new Stack<>();
Stack<Integer> help = new Stack<>();
public SortedStack() {
super();
}
public void push(int val) {
if(isEmpty()){
data.push(val);
//把辅助栈的元素全部压入数据栈
while (!help.empty()){
data.push(help.pop());
}
} else {
int top = peek();//将栈顶元素与要插入的元素比较
if(top >= val){
data.push(val);
while (!help.empty()){
data.push(help.pop());
}
} else {
//因为最小的在栈顶,因此,把数据栈中的元素,将数据栈栈顶元素移到辅助栈,在查看插入情况
help.push(data.pop());
push(val);
}
}
}
public void pop() {
if(!data.empty()){
data.pop();
}
}
public int peek() {
if(isEmpty()){
return -1;
}
return data.peek();
}
public boolean isEmpty() {
if(data.empty()){
return true;
}
//非空,返回false
return false;
}
}
堆栈排序
最新推荐文章于 2021-08-05 16:33:05 发布