打卡:12.8

用一个栈实现另一个栈的排序

http://www.nowcoder.com/questionTerminal/ff8cba64e7894c5582deafa54cca8ff2

import java.util.*;
import java.io.*;
public class Main{
    public static void main(String[] args) throws Exception{
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        int N = Integer.parseInt(br.readLine());
        String[] strs = br.readLine().trim().split(" ");
        int[] nums = Arrays.stream(strs).mapToInt(Integer::parseInt).toArray();
        Stack<Integer> stack_in = new Stack<>();
        for(int i = N - 1; i >= 0; i--){
            stack_in.push(nums[i]);
        }
        sort(stack_in);
        System.out.print(stack_in.pop());
        while(!stack_in.isEmpty()){
            System.out.print(" " + stack_in.pop());
        }
    }
    //排序
    public static void sort(Stack<Integer> stack_in){
        if(stack_in.size() < 2){
            return;
        }
        Stack<Integer> stack_help = new Stack<>();
        while(!stack_in.isEmpty()){
            int cur = stack_in.pop();
            while(!stack_help.isEmpty() && stack_help.peek() < cur){
                stack_in.push(stack_help.pop());
            }
            stack_help.push(cur);
        }
        while(!stack_help.isEmpty()){
            stack_in.push(stack_help.pop());
        }
    }
}
全部评论

相关推荐

点赞 收藏 评论
分享
牛客网
牛客企业服务