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

问题描述

如题。
输入 栈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);//再入栈
	}
}

posted on   coding_gaga  阅读(142)  评论(0编辑  收藏  举报

< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

导航

统计

点击右上角即可分享
微信分享提示