【左神算法】实现一个栈的逆序,但是只能用递归函数的这个栈本身的操作来实现,而不能用自己申请另外的数据结构

1.题目描述

实现一个栈的逆序,但是只能用递归函数的这个栈本身的操作来实现,而不能用自己申请另外的数据结构

2.思路&code

思路

1.栈的逆序,如果不借助任何的数据结构,我们只能依靠递归函数来实现。而这个思路也是不容易想到的。首先,我们需要一个get()函数,每次返回栈底的元素,并在栈中移除。递归函数是一个系统调用栈实现。因此很容易实现。第二个函数,reverse函数,将栈中的元素进行逆序。

code

package com.ncst.algo;

import java.util.Stack;

/**
 * @author i
 * @create 2020/6/29 19:25
 * @Description 实现一个栈的逆序,但是只能用递归函数的这个栈本身的操作来实现,而不能用自己申请另外的数据结构
 *
 *   3 2 1  1 2 3
 */
public class StackResve {

    //移除栈底元素并返回。
    public static int get(Stack<Integer> stack){
        int result = stack.pop();//
        if(stack.isEmpty()){
            return result;
        }else {
            int last = get(stack);
            stack.push(result);
            return last;
        }
    }

    //将栈中元素逆序的方法
    public static void reverse(Stack<Integer> stack){
        if (stack.isEmpty()){
            return;
        }
        int i = get(stack);
        reverse(stack);
        stack.push(i);
    }


    public static void main(String[] args) {
        Stack<Integer> stack = new Stack<>();
        stack.push(3);
        stack.push(2);
        stack.push(1);

        reverse(stack);

        while (!stack.isEmpty()){
            System.out.print(stack.pop()+"\t");
        }
    }


}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章