Java:仅借助一个辅助栈实现对栈中数据的排序

·
编程 算法 no tag March 12, 2016
package facetest.StackSort;

import java.util.Stack;

public class SortWithOneHelpStack {
    public static void sortStackByStack(Stack<Integer> stack){
        Stack<Integer> help=new Stack<>();
        while(!stack.isEmpty()){

            /*逻辑冗余版*/
            /*int firt=stack.pop();
            if( help.isEmpty()||help.peek()>firt){
                help.push(firt);
            }else {
                while(!help.isEmpty()&&help.peek()<firt){
                    stack.push(help.pop());
                }
                help.push(firt);
            }*/

            /*逻辑精简版*/
            int first=stack.pop();
            while(!help.isEmpty()&&help.peek()<first){
                stack.push(help.pop());
            }
            help.push(first);
        }

        while (!help.isEmpty()){
            stack.push(help.pop());
        }
    }

    public static void main(String[] args){
        Stack<Integer> stack=new Stack<>();
        stack.push(3);
        stack.push(7);
        stack.push(8);
        stack.push(5);
        stack.push(5);
        stack.push(1);
        sortStackByStack(stack);
        while (!stack.isEmpty()){
            System.out.println(stack.pop());
        }
    }
}
  • 一个不易发现也不经常遇到的Bug
  • 树的遍历:DFS及BFS
取消回复

说点什么?

© 2021 Self. Using Typecho & Moricolor.