要求:
一个栈的元素为整型,现在想将该栈的从栈顶到底按从小到大的顺序排序,只许申请一个栈。
思考:
将要排序的栈记为stack,申请辅助的栈记为help,在stack栈执行pop操作,弹出的元素记为cur,如果cur大于help的栈顶元素,则将cur压入help;如果cur小于help的栈顶元素,则弹出help栈顶元素压入stack直到cur的值大于等于help的栈顶元素。依次运行,直到stack为空之后,把help的栈元素依次压入stack栈里即可。
实现代码:
package algorithm_5;
import java.util.Stack;
public class algorithm_5 {
public static void sortStackByStack(Stack<Integer> stack) {
Stack<Integer> help = new Stack<Integer>();
while(!stack.isEmpty()){
int cur = stack.pop();
while(!help.isEmpty() && help.peek()< cur){
stack.push(help.pop());
}
help.push(cur);
}
while (!help.isEmpty()){
stack.push(help.pop());
}
}
public static void main(String[] args) {
Stack<Integer> s ;
s = new Stack<Integer>();
s.push(1);
s.push(5);
s.push(3);
s.push(4);
s.push(2);
sortStackByStack(s);
while(!s.isEmpty()){
System.out.println(s.pop());
}
}
}
实验结果: