zoukankan      html  css  js  c++  java
  • 如何仅用递归函数和栈操作逆序一个栈

    题目

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

    要求

    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中查看

  • 相关阅读:
    QSet<T>自定义类型需要定义==和qHash()函数
    《左耳听风》-ARTS-打卡记录-第十三周
    Windows中对窗口进行剪切
    Markdown 编写规范
    【洛谷 P1033】自由落体
    【GOJ 3032】司愁之路
    动态规划基础 3-解题报告
    前缀、中缀、后缀互相转换
    【GOJ 3015】疯狂外星人
    【GOJ 3010】有趣的数
  • 原文地址:https://www.cnblogs.com/xiaohunshi/p/5706222.html
Copyright © 2011-2022 走看看