解题思路
假设需要被排序的栈为stack 申请一个栈helper,当栈stack不为空的时,出栈stack栈顶的元素,标记为cur 若helper为空或者stack栈顶的元素大于等于cur,将cur压入helper中,否则将helper中的元素弹出到stack中,直到helper为空或helper栈顶的元素小于等于cur,再将cur压入helper中,如此反复,直到stack为空(此时,helper中的元素已经有序),再将helper中的元素一一压回stack中即可。
代码
package TestNode
.StackAndQueue
;
import java
.util
.Stack
;
public class OrderStackByStack {
public static void orderStack(Stack
<Integer> stack
){
Stack
<Integer> helper
= new Stack<>();
while (!stack
.isEmpty()){
if (helper
.isEmpty() || stack
.peek()>=helper
.peek()){
helper
.push(stack
.pop());
}else {
Integer cur
= stack
.pop();
while(!helper
.isEmpty() && cur
<helper
.peek()){
stack
.push(helper
.pop());
}
helper
.push(cur
);
}
}
while (!helper
.isEmpty()){
stack
.push(helper
.pop());
}
}
public static void main(String
[] args
) {
Stack
<Integer> stack
= new Stack<>();
stack
.push(1);
stack
.push(3);
stack
.push(2);
stack
.push(8);
stack
.push(5);
orderStack(stack
);
while (!stack
.isEmpty()){
System
.out
.println(stack
.pop());
}
}
}
转载请注明原文地址: https://yun.8miu.com/read-132810.html