栈的逆转与栈的排序

栈的逆转与栈排序。

关键:①、模块化编程;②、递归。

import java.util.Stack;

public class StackLearn {
    public static void main(String[] args) {
        Stack stack = new Stack<>();
        stack.push(1);
        stack.push(8);
        stack.push(2);
        stack.push(5);
        stack.push(6);
        System.out.println(stack);
        //Reverse(stack);
        //bottomToTop(stack);
        stackSort(stack);
        System.out.println(stack);

    }

    //1-1、栈底元素移动到栈顶
    public static void bottomToTop(Stack s){
        int top1 = s.pop();
        if (!s.empty()){
            bottomToTop(s);
            int top2=s.pop();
            s.push(top1);
            s.push(top2);
        }else {
            s.push(top1);
        }
    }

    //1-2、栈的逆转
    static void Reverse(Stack s){
        if (s.isEmpty())return;
        bottomToTop(s);
        int top = s.pop();
        Reverse(s);
        s.push(top);
    }

    //2-1、最小元素移动到栈顶
    public static void MinMoveToTop(Stack stk){
        if(stk.isEmpty()) return;

        int top1=stk.pop();
        if (!stk.isEmpty()){
            MinMoveToTop(stk);
            int top2=stk.pop();
            if(top1>top2){
                stk.push(top1);
                stk.push(top2);
            }else{
                stk.push(top2);
                stk.push(top1);
            }
        }else {
            stk.push(top1);
        }
    }


    //2-2、栈排序
    public static void stackSort(Stack stk){

        if(stk.isEmpty()) return ;

        MinMoveToTop(stk);

        int top1=stk.pop();

        stackSort(stk);
        stk.push(top1);
    }
}

 

你可能感兴趣的:(————算法训练————,#,JavaSE)