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

题目

将一个栈里面的元素逆序,只能用递归函数来实现,不能用其他数据结构。

要求

  1. 只能用递归函数来实现
  2. 可以使用现成的栈类型

思路

为了将栈逆序,只需要按顺序将栈顶至栈底的元素拿出并移除,放置到栈顶中,这样就可以将栈逆序。

代码

实现代码

import java.util.Stack;

/**
 * Created by wentian on 16/6/10.
 */
public class ReverseStack<T> {
    public Stack<T> reverseStack(Stack<T> stackData) {
        int size = stackData.size();
        T pushElement = null;
        for (int i = 0; i < size; i++) {
            pushElement = getAndPopBottomElement(stackData, i);
            stackData.push(pushElement);
        }

        return stackData;
    }

    public T getAndPopBottomElement(Stack<T> stackData, int index) {
        T bottom = stackData.pop();
        if (0 == index)
            return bottom;

        T result = getAndPopBottomElement(stackData, index - 1);
        stackData.push(bottom);
        return result;
    }
}

测试代码

import org.junit.Test;

import java.util.Stack;

import static org.junit.Assert.*;

/**
 * Created by wentian on 16/6/10.
 */
public class ReverseStackTest {
    @Test
    public void reverseStack() throws Exception {
        ReverseStack<Integer> reverseStack = new ReverseStack<Integer>();

        Stack<Integer> stackData = new Stack<Integer>();
        stackData.push(1);
        stackData.push(2);
        stackData.push(3);

        reverseStack.reverseStack(stackData);

        while(!stackData.empty()){
            System.out.println(stackData.pop());
        }
    }
}

在github中查看

原文地址:https://www.cnblogs.com/xiaohunshi/p/5706222.html