3.如何仅用递归函数和栈操作逆序一个栈

来源:互联网 发布:动漫网站源码整套 编辑:程序博客网 时间:2024/05/29 17:52

题目:实现一个栈中的元素的逆序,只能用递归来实现,不能使用其他数据结构


思路:我对递归不是很熟悉,看了书上的代码,了解了其中的意思后敲了一份,主要是要递归取出该栈中的每一个元素,然后将元素再压栈。所以有两个函数,一个就是取出栈底元素,另一个就是压栈操作,(其实如果直接pop就不用递归了,我觉得这题的意义不大,只是单纯考察递归的使用,因为不用递归更方便操作)


import java.util.Stack;public class ReverseStackByrecursion {public int getBottomElement(Stack<Integer> stack){int tmp = stack.pop();if(stack.isEmpty())return tmp;else{int last = getBottomElement(stack);stack.push(tmp);return last;}}public void reverse(Stack<Integer> stack){if(stack.isEmpty())return;int e = getBottomElement(stack);reverse(stack);stack.push(e);}}


0 0