229. 栈排序
中文English
请设计一种方法将一个栈进行升序排列 (最大的数在最上面)。
你可以使用另外一个栈来辅助操作,但不可将这些数复制到另外一个数据结构中 (如,数组)。
样例
给一个栈:
| |
|3|
|1|
|2|
|4|
-
排序之后:
| |
|4|
|3|
|2|
|1|
-
栈会被序列化为[4,2,1,3]
,也就是说最右边是栈顶。
注意事项
时间复杂度为O(n^2)的算法也可以通过测试
public class Solution {
/*
* @param stk: an integer stack
* @return: void
*/
public void stackSorting(Stack<Integer> stk) {
// write your code here
Stack<Integer> st = new Stack<>();
if(stk.size()<=0) return ;
st.push(stk.pop());
while(!stk.isEmpty()){
int temp = stk.pop();
if(temp<=st.peek()) st.push(temp);
else {
while(!st.isEmpty() &&st.peek()<temp) stk.push(st.pop());
st.push(temp);
}
}
while(!st.isEmpty()){
stk.push(st.pop());
}
}
}