zoukankan      html  css  js  c++  java
  • 《程序员代码面试指南》第一章 栈和队列 用一个栈实现另一个栈的排序

    题目

    将一个存放整数的栈,从栈顶到栈底 由小到大排列,只能用一个辅助栈,可以用辅助变量,不能用其他数据结构
    

    java程序

    /**
     * @Description:用一个栈实现另一个栈的排序
     * @Author: lizhouwei
     * @CreateDate: 2018/4/5 16:10
     * @Modify by:
     * @ModifyDate:
     */
    public class Chapter1_5 {
    
        //借助一个辅助栈排序
        public Stack<Integer> sort(Stack<Integer> stack){
            Stack<Integer> heleStack = new Stack<Integer>();//辅助栈
            int vlaue = 0; //辅助变量 暂存栈中弹出的元素
            while(!stack.isEmpty()){
                vlaue =   stack.pop();
                while(!heleStack.isEmpty() && vlaue< heleStack.peek()){
                    stack.push(heleStack.pop());
                }
                heleStack.push(vlaue);
            }
            // 此时 辅助栈中栈顶到栈底 是从大到小的,再放进原栈中,则元素为从小到大
            while(!heleStack.isEmpty()){
                stack.push(heleStack.pop());
            }
            return stack;
        }
    
        //测试
        public static void main(String[] args){
            Chapter1_5 chapter = new Chapter1_5();
            Stack<Integer> stack = new Stack<Integer>();
            for(int i=10,j=11;i<20;i=i+2,j=j+10) {
                stack.push(j);
                stack.push(i);
            }
            stack = chapter.sort(stack);
             while(!stack.isEmpty()){
                System.out.print(stack.pop()+" ");
            }
        }
    }
    
  • 相关阅读:
    CF1580B Mathematics Curriculum
    [机房测试]变异大老鼠
    http_缓存
    UDP_概述
    记录: webAssembly 延申
    Event
    NetWork_timeLine
    基于Typora的Latex代码书写并移植到word中
    ZooKeeper学习总结
    HBase学习总结
  • 原文地址:https://www.cnblogs.com/lizhouwei/p/8723146.html
Copyright © 2011-2022 走看看