输入: 5 5 8 4 3 6 输出: 8 6 5 4 3
原来的栈为 stack,辅助栈为 help。不断从 stack 中弹出元素,弹出的元素记为 cur。
import java.util.Scanner; import java.util.Stack; public class Main{ public static void sortStack(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> stack = new Stack<>(); Scanner scanner = new Scanner(System.in); int n = scanner.nextInt(); for(int i=0;i<n;i++){ stack.push(scanner.nextInt()); } sortStack(stack); while(!stack.isEmpty()){ System.out.print(stack.pop()+" "); } } }