[程序员代码面试指南]栈和队列-仅用递归函数和栈操作来逆序一个栈(递归)

问题描述

如题。
输入 栈12345
输出 栈54321

解题思路

用两个递归函数:

  • 第一个可以将栈底元素弹出
  • 第二个借助第一个可以实现栈逆序

代码

import java.util.Stack;

public class Main {
    public static void main(String args[]) {
        Stack<Integer> s=new Stack<>();
        s.push(1);
        s.push(2);
        s.push(3);
        for(int val:s) {
            System.out.println(val);
        }
        
        reverse(s);
        for(int val:s) {
            System.out.println(val);
        }
    }
    
    public static int popBottom(Stack<Integer> s) {
        int val=s.pop();
        if(s.empty()) {
            return val;
        }
        int bottomVal=popBottom(s);
        s.push(val);
        return bottomVal;
    }
    
    public static void reverse(Stack<Integer> s) {
        if(s.empty()) {
            return;
        }
        int val=popBottom(s);
        reverse(s);
        s.push(val);
    }
}

猜你喜欢

转载自www.cnblogs.com/coding-gaga/p/10872718.html