将要排序的栈记为stack,申请辅助的栈记为help,在stack栈执行pop操作,弹出的元素记为cur,如果cur大于help的栈顶元素,则将cur压入help;如果cur小于help的栈顶元素,则弹出help栈顶元素压入stack直到cur的值大于等于help的栈顶元素。依次运行,直到stack为空之后,把help的栈元素依次压入stack栈里即可。
package com.bc;
import java.util.Stack;
public class StackTest {
public static void main(String[] args) {
Stack<Integer> stack=new Stack<Integer>();
stack.push(3);
stack.push(5);
stack.push(2);
stack.push(7);
stack.push(6);
sortstack(stack);
while(!stack.empty()){
System.out.println(stack.pop());
}
}
private static void sortstack(Stack<Integer> stack) {
Stack<Integer> help=new Stack<Integer>();
while(!stack.empty()){
int cur=stack.pop();
while(!help.empty()&&help.peek()>cur){
stack.push(help.pop());
}
help.push(cur);
}
while (!help.isEmpty()){
stack.push(help.pop());
}
}
}