zoukankan      html  css  js  c++  java
  • 算法总结之 如何用递归函数和栈操作逆序一个栈

    一个栈一次压入 1 2 3 4 5 那么从栈顶到栈底分别为 5 4 3 2 1. 将这个栈转置后,从栈顶到栈底为 1  2 3 4 5  实现栈中元素的逆序

    要求只能用 递归函数实现 

    代码:

    package TT;
    
    import java.util.Stack;
    
    public class Test122 {
    
    	public static int getAndRemoveLaseElement(Stack<Integer> stack){
    		 int result = stack.pop();
    		 if(stack.isEmpty()){
    			return result;
    		 }else {
    			int last = getAndRemoveLaseElement(stack);
    			stack.push(result);
    			return last;
    		}
    		 
    	}
    	
    	
    	public static void reverse( Stack<Integer> stack){
    		if(stack.isEmpty()){
    			  return;
    		}
    		
    		int i = getAndRemoveLaseElement(stack);
    		reverse(stack);
    		stack.push(i);
    		
    		
    		
    	}
    	
    	
    	
    	
    	
    }
    

      这个代码是这么理解:

    最后一层递归   空的时候  return result=1   last此时就是1了 然后push进去的都是result~~~~

  • 相关阅读:
    英雄大乱斗
    深浅拷贝(copy)
    myleecode
    代码量简单统计
    pandas 模块 05
    matplotlib 模块 07
    KVC 和KVO浅谈
    iOS开发中懒加载的使用和限制
    关于空白模板插件的使用
    UIImageC处理
  • 原文地址:https://www.cnblogs.com/toov5/p/7511341.html
Copyright © 2011-2022 走看看