• 《程序员代码面试指南》第一章 栈和队列 用一个栈实现另一个栈的排序


    题目

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

    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()+" ");
            }
        }
    }
    
  • 相关阅读:
    Design Pattern: Gof
    ZT --- extern "C"用法详解 2010-08-21 19:14:12
    OCR
    Linux strace命令
    wireshark esp
    https://sourceware.org/gdb/onlinedocs/gdb/Forks.html
    12306网上买火车票选择上中下铺的方法
    gdb调试有fork的程序
    named piped tcp proxy
    bash 提示用户输入 choice
  • 原文地址:https://www.cnblogs.com/lizhouwei/p/8723146.html
Copyright © 2020-2023  润新知