例子:
Input : [34, 3, 31, 98, 92, 23]
Output : [3, 23, 31, 34, 92, 98]
Input : [3, 5, 1, 4, 2, 8]
Output : [1, 2, 3, 4, 5, 8]
算法:
- 创建一个临时堆栈,比如 tmpStack。
- 当输入堆栈不为空时,请执行以下操作:
- 从输入堆栈中弹出一个元素,称之为 temp
- 当临时堆栈不为空且临时堆栈顶部大于 temp 时,
从临时堆栈弹出并将其推送到输入堆栈 - 在临时堆栈中推送temp
import java.util.*;
class SortStack
{
public static Stack<Integer> sortstack(Stack<Integer>
input)
{
Stack<Integer> tmpStack = new Stack<Integer>();
while(!input.isEmpty())
{
//创建一个临时栈
int tmp = input.pop();
//如果临时栈不为空且临时栈顶元素大于输入栈顶元素,则将临时栈顶的元素存入到输入栈
while(!tmpStack.isEmpty() && tmpStack.peek()
> tmp)
{
input.push(tmpStack.pop());
}
tmpStack.push(tmp);
}
return tmpStack;
}
public static void main(String args[])
{
Stack<Integer> input = new Stack<Integer>();
input.add(34);
input.add(3);
input.add(31);
input.add(98);
input.add(92);
input.add(23);
Stack<Integer> tmpStack=sortstack(input);
System.out.println("Sorted numbers are:");
while (!tmpStack.empty())
{
System.out.print(tmpStack.pop()+" ");
}
}
}