栈和队列之仅用递归函数和栈操作逆序一个栈

import java.util.Stack;

/**
 * recursion 递归的意思
 * @author chenyu
 * 题目:仅用递归函数和栈操作逆序一个栈,列如一次压入1、2、3、4、5 栈顶到栈底是5、4、3、2、1
 * 将这个栈转置后栈顶到栈底依次为1、2、3、4、5
 * 
 * 思路:需要两递归函数 
 *         第一个递归函数是去除栈底并且得到栈底的函数
 *         第二个递归函数是依次调用第一个递归函数,然后再压入栈
 */
public class ReverseStackByRecursion {
	public static void main(String[] args) {
		Stack<Integer> stack=new Stack<Integer>();
		stack.push(1);
		stack.push(2);
		stack.push(3);
		stack.push(4);
		stack.push(5);
		reverse(stack);
       while(!stack.empty()){
    	   System.out.println(stack.pop());
       }
}
	/**
	 * 去除栈底并且得到栈底的函数
	 * @param stack
	 * @return
	 */
          public static int getAndRemoveLastElement(Stack<Integer> stack){
        	   int result =stack.pop();
        	   if(stack.isEmpty()){
        		   return result;
        	   }else{
        		    int last=getAndRemoveLastElement(stack);
        		    stack.push(result);
        		    return last;
        	   }
          }
          /**
           * 得到的最后一个元素递归压入栈
           * @param stack
           */
          public static void reverse(Stack<Integer> stack){
        	  if(stack.empty()){
        		  return;
        	  }
        	  int i=getAndRemoveLastElement(stack);
        	  reverse(stack);
        	  stack.push(i);
          }
}


结果:

1

2

3

4

5

你可能感兴趣的:(栈和队列,用递归函数和栈操作逆序一个栈)