题目描述
请编写一个程序,按升序对栈进行排序(即最大元素位于栈顶),要求最多只能使用一个额外的栈存放临时数据,但不得将元素复制到别的数据结构中。
给定一个int[] numbers(C++中为vector<int>),其中第一个元素为栈顶,请返回排序后的栈。请注意这是一个栈,意味着排序过程中你只能访问到第一个元素。
测试样例:
[1,2,3,4,5]
返回:[5,4,3,2,1]
思路:
每次用一个temp来临时存stack1弹出的变量,然后从s2中依次倒入s1,直到temp可以放入合适的位置。
如果s1中的temp比stack2栈顶值大 就会直接放入stack2
import java.util.*;
public class TwoStacks {
public ArrayList<Integer> twoStacksSort(int[] numbers) {
// write code here
ArrayList<Integer> arrayList = new ArrayList<>();
if(numbers.length==0)return arrayList;
Stack<Integer> stack = new Stack<>();
Stack<Integer> ascstack = new Stack<>();
for(int i =0;i<numbers.length;i++){
stack.push(numbers[i]);
}
while(!stack.isEmpty()){
int temp = stack.pop();
while(!ascstack.isEmpty()){
if(temp<ascstack.peek()){
//将大于temp的数转到stack中
stack.push(ascstack.pop());
}
else{break;}
}
ascstack.push(temp);
}
while(!ascstack.isEmpty()){
arrayList.add(ascstack.pop());
}
return arrayList;
}
}