zoukankan      html  css  js  c++  java
  • 仅用递归函数和栈操作逆序一个栈

    要求:

    一个栈依次压入1,2,3,4,5那么从栈顶到栈底分别为5,4,3,2,1。将这个栈转置后,从栈顶到栈底为1,2,3,4,5,也就是实现栈中元素的逆序,但是只能用递归函数来实现,而不能用另外的数据结构。

    5 

    import java.util.Stack;
    
    public class Problem03_ReverseStackUsingRecursive {
        
        /*
         * 递归得到栈底元素
         */
        public static int getAndRemoveLastElement(Stack<Integer> stack){
            int result = stack.pop();
            if (stack.isEmpty()){
                return result;            
            } else {
                int lastElement = getAndRemoveLastElement(stack);
                stack.push(result);
                return lastElement;
            }        
        }
        
        /*
         * 逆序
         */
        public static void reverse(Stack<Integer> stack) {
            if (stack.isEmpty()) {
                return;
            }
            int i = getAndRemoveLastElement(stack);
            reverse(stack);
            stack.push(i);
        }
        
    
        public static void main(String[] args) {
            Stack<Integer> test = new Stack<Integer>();
            test.push(1);
            test.push(2);
            test.push(3);
            test.push(4);
            test.push(5);
            System.out.println(test);
            reverse(test);
            System.out.println(test); 
            while (!test.isEmpty()) {
                System.out.println(test.pop());
            }
    
        }
    
    }

    运行结果:

    [1, 2, 3, 4, 5]
    [5, 4, 3, 2, 1]
    1
    2
    3
    4
    5
  • 相关阅读:
    团队冲刺第一天
    第八周进度报告
    团队会议01
    《梦断代码》阅读笔记(三)
    《梦断代码》阅读笔记(二)
    《梦断代码》阅读笔记(一)
    SCRUM第六天
    SCRUM第五天
    大白话strom——问题收集(持续更新ing)
    maven环境快速搭建(转)
  • 原文地址:https://www.cnblogs.com/xiyuan2016/p/6797230.html
Copyright © 2011-2022 走看看