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

    题目

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

    难度 ♥

    思路

    • 选择一个stack.pop()弹出的栈(旧栈)顶元素作为比较值,装入到一个新的栈中

    • 用新栈的栈顶值比较旧栈再弹出的值

    • 如果新栈的值大于旧栈的值,则将旧栈的值装入到新栈中

    • 如果新栈的值小于旧栈的值,则将新栈的值弹出装入到旧栈中

       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());
    }
    ```
    看完上面的图,到这已经很好理解了,没必要在画图了...

    实现

    package com.test.desc;
    import org.junit.Test;
    import java.util.Stack;
    
    /**
     * @author lorem 
     * @date 2018.9.11
     */
    public class TestStackDesc {
        @Test
        public void test(){
            Stack<Integer> stack = new Stack<Integer>();
            stack.push(1);
            stack.push(3);
            stack.push(2);
    
            sortStackByStack(stack);
            while(!stack.isEmpty()){
                System.out.println(stack.pop());
            }
        }
        public 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());
            }
        }
    }
    
    
    - The End -

    知识共享许可协议 本作品采用知识共享署名-非商业性使用 4.0 国际许可协议进行许可。

  • 相关阅读:
    英文词频统计
    字符串练习
    第八周
    第七周
    第五周
    第六周
    第三周
    第四周
    第二周
    第一周作业
  • 原文地址:https://www.cnblogs.com/hoochanlon/p/9676666.html
Copyright © 2011-2022 走看看