zoukankan      html  css  js  c++  java
  • 用一个栈实现另一个栈的排序

    要求:

        在一个栈中元素的类型为整型,现在想将该栈从栈顶到栈底按从大到小的顺序排序,只许申请一个栈,除此之外,可以申请其他变量,但是不能申请额外的数据结构

    解题思路:

         待排序的栈stack, 辅助栈help。 在stack上执行pop操作,记元素为cur

         if cur <= 【help 的栈顶元素】,cur 压入help栈中;

         else cur > 【help 的栈顶元素】,逐一弹出help, 直到cur <= 【help 的栈顶元素】,在将cur压入help

          一直执行以上操作,直到stack中的全部元素都导入help栈中,(此时从栈顶到栈底:有小到大),最后,将help栈中的元素,pop一下,排序

    import java.util.Stack;
    
    public class Problem05_StackSortStack {
        /*
         * 待排序的栈stack, 辅助栈help。 在stack上执行pop操作,记元素为cur
                if cur <= 【help 的栈顶元素】,cur 压入help栈中;
                else cur > 【help 的栈顶元素】,逐一弹出help, 直到cur <= 【help 的栈顶元素】,在将cur压入help
          一直执行以上操作,直到stack中的全部元素都导入help栈中,(此时从栈顶到栈底:有小到大),最后,将help栈中的元素,pop一下,排序
         */
        public static void sortStackByStack(Stack<Integer> stack) {
            Stack<Integer> help = new Stack<Integer>();
            while (!stack.isEmpty()) {
                int cur = stack.pop();
                while (!help.isEmpty() && help.peek() < cur) {
                    stack.push(help.pop());
                }
                help.push(cur);
            }
            while (!help.isEmpty()) {
                stack.push(help.pop());
            }
        }
        
    
        public static void main(String[] args) {
            Stack<Integer> stack = new Stack<Integer>();
            stack.push(3);
            stack.push(1);
            stack.push(6);
            stack.push(2);
            stack.push(5);
            stack.push(4);
            sortStackByStack(stack);        
            int stack_size= stack.size();
            System.out.println("stack元素是:");
            for (int size=0; size < stack_size; size ++){            
                System.out.println(stack.pop());
            }
            
            
        }
    
    }

    执行结果:

    stack元素是:
    6
    5
    4
    3
    2
    1
  • 相关阅读:
    呀?这就是锁(二)?
    呀?这就是锁(一)?
    线程的建立
    Mybatis基础使用简介
    使用apache+tomcat+mod_jk.so实现集群
    HttpClient使用详解
    HttpClient基础用法
    Collection集合学习(二)———List接口与具体实现
    Docker学习总结(二)—— 镜像,容器
    Docker学习总结(一)—— namespace,cgroup机制
  • 原文地址:https://www.cnblogs.com/xiyuan2016/p/6830821.html
Copyright © 2011-2022 走看看