用一个栈给另外一个栈排序
2019-05-29 本文已影响0人
事件_666
import java.util.Stack;
public class Problem_05_StackSortStack {
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> stack = new Stack<Integer>();
stack.push(3);
stack.push(1);
stack.push(6);
stack.push(2);
stack.push(5);
stack.push(4);
sortStackByStack(stack);
System.out.println(stack.pop());
System.out.println(stack.pop());
System.out.println(stack.pop());
System.out.println(stack.pop());
System.out.println(stack.pop());
System.out.println(stack.pop());
}
}