3.6

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]



 


 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值