只利用一个栈和常数个变量,不再使用其他数据结构,排序给定的栈。
import java.util.Stack;
public class Pro_5_DoubleStackSort {
private Stack<Integer> stack;
private Stack<Integer> help;
public Pro_5_DoubleStackSort()
{
stack =new Stack<>();
help = new Stack<>();
}
public void sort()
{
while(!stack.isEmpty())
{
int cur=stack.pop();
//使help栈中顺序始终是栈顶小,栈底大
while(!help.isEmpty() && help.peek()<cur)
{
stack.push(help.pop());
}
help.push(cur);
}
//再将help栈元素依次 入stack栈中,形成顺序:栈底小,栈顶大
while(!help.isEmpty())
{
System.out.println(help.peek());
//
stack.push(help.pop());
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
Pro_5_DoubleStackSort test = new Pro_5_DoubleStackSort();
test.stack.push(3);
test.stack.push(1);
test.stack.push(2);
test.sort();
}
}