题目描述
请编写一个程序,按升序对栈进行排序(即最大元素位于栈顶),要求最多只能使用一个额外的栈存放临时数据,但不得将元素复制到别的数据结构中。
给定一个int[] numbers(C++中为vector<int>),其中第一个元素为栈顶,请返回排序后的栈。请注意这是一个栈,意味着排序过程中你只能访问到最后一个元素。
测试样例:
[1,2,3,4,5]
返回:[5,4,3,2,1]
思路:
1.新建两个栈,栈1用来保存排序后的值,栈2用来存储临时数据。
2.遍历数组,若数组的值比当前栈1的数据小,那么把当前栈1的数据弹到栈2中;接着把当前数据压入栈1,最后把栈2的元素压回栈1。
3.移除弹出栈1的元素,得到最终的结果
代码
import java.util.*;
public class TwoStacks {
public ArrayList<Integer> twoStacksSort(int[] numbers) {
ArrayList<Integer> result = new ArrayList<Integer>();
Stack<Integer> stack1 = new Stack<Integer>(); //存储排完序的值
Stack<Integer> stack2 = new Stack<Integer>(); //存储临时数据(若numbers[i]的值小于stack1的值,先把值弹到栈2,当把当前值压入栈1后,把栈2的值也进压入栈1)
for(int i : numbers) {
if(stack1.isEmpty()) { //当栈1为空是可直接压入
stack1.push(i);
}else {
while(!(stack1.isEmpty()) && stack1.peek() > i) { //把大于当前的值压入栈2
stack2.push(stack1.pop());
}
stack1.push(i);
while(!stack2.isEmpty()) { //把当前元素压入栈1后,需要把原来的元素还原
stack1.push(stack2.pop());
}
}
}
while(!stack1.isEmpty()) {
result.add(stack1.pop());
}
return result;
}
}