Topic:Write a program to sort a stack in ascending order (with biggest items on top). You may use additional stacks to hold items, but you may not copy the elements into any other data structure (such as an array). The stack supports the following operations: push, pop, peek, and isEmpty.
// 方法1:use two additional stacks. Searching the minimum and push
onto a new stack, when searching, another stack is needed as a buffer. Because to search minimum, we need to pop elements and push them onto the buffer. 先从未排序的栈弹出一个,放到排好序的;再一个一个弹出,往新stack里面插入,那个栈里面总是排好序的;插入的时候:只要比插入的小,就弹出到buffer,插入后再把buffer的压回排好序的.
// 方法2:only use one additional stack. 先从未排序的栈弹出一个,放到排好序的;再弹出一个,与排好序的比较(依次pop),找到合适的位置,在把原来的push回来。复杂度均为:Time:O(n2), Space: O(n).
import java.util.Stack;
public class SortStack {
Stack<Integer> stack1, stack2, buffer;
public SortStack(){
stack1=new Stack<Integer>();
stack2=new Stack<Integer>();
buffer=new Stack<Integer>();
}
public void initial(int[] input){
for(int i:input){
stack1.push(i);
}
}
//先从未排序的栈弹出一个,放到排好序的;再一个一个弹出,往新stack里面插入,那个栈里面总是排好序的;插入的时候:只要比插入的大,就弹出到buffer,插入后再把buffer的压回排好序的
public Stack<Integer> sort(){
while(!stack1.isEmpty()){
int cur=stack1.pop();
if(stack2.isEmpty()){stack2.push(cur);}
while(!stack2.isEmpty()&&stack2.peek()>cur){
buffer.push(stack2.pop());
}
stack2.push(cur);
while(!buffer.isEmpty()){
stack2.push(buffer.pop());
}
}
return stack2;
}
public static void main(String[] args){
SortStack stack = new SortStack();
int[] input = {3,2,1,4,5,6,7,7,7,8};
stack.initial(input);
System.out.println(stack.sort());
}
}
import java.util.Stack;
public class SortStack {
Stack<Integer> stack1, stack2;
public SortStack(){
stack1=new Stack<Integer>();
stack2=new Stack<Integer>();
}
public void initial(int[] input){
for(int i:input){
stack1.push(i);
}
}
//先从未排序的栈弹出一个,放到排好序的;再弹出一个,与排好序的比较(依次pop),找到合适的位置,在把原来的push回来
//push回来这一步不用写,在循环里,因为它们已经是排好序的,所以stack2.peek()>cur始终为假,被stack2.push(cur)实现了
public Stack<Integer> sort(){
while(!stack1.isEmpty()){
int cur=stack1.pop();
if(stack2.isEmpty()){stack2.push(cur);}
while(!stack2.isEmpty()&&stack2.peek()>cur){
stack1.push(stack2.pop());
}
stack2.push(cur);
}
return stack2;
}
public static void main(String[] args){
SortStack stack = new SortStack();
int[] input = {3,2,1,4,5,6,7,7,7,8};
stack.initial(input);
System.out.println(stack.sort());
}
}
//结果
[1, 2, 3, 4, 5, 6, 7, 7, 7, 8, 8]