栈排序(中等)
2020年10月14日
题目来源:力扣
解题
辅助栈来存放主栈比push的值大的元素
class SortedStack {
private Stack<Integer> st1;
private Stack<Integer> st2;
public SortedStack() {
st1=new Stack<>();
st2=new Stack<>();
}
public void push(int val) {
if(st1.empty())
st1.push(val);
else{
while(!st1.empty() && st1.peek()<val){
st2.push(st1.pop());
}
st1.push(val);
while(!st2.empty()){
st1.push(st2.pop());
}
}
}
public void pop() {
if(!st1.empty())
st1.pop();
}
public int peek() {
if(!st1.empty())
return st1.peek();
return -1;
}
public boolean isEmpty() {
return st1.empty();
}
}
/**
* 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();
*/