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

  • 相关阅读:
    mysql concat_ws 与 concat 多字段模糊匹配应用
    logstash marking url as dead 问题解决
    IntelliJ IDEA(四) :Settings(上)
    IntelliJ IDEA(三) :常用快捷键
    IntelliJ IDEA(二) :面板介绍
    IntelliJ IDEA(一) :安装与破解(支持最新2020.1)
    Echo框架
    Goland 结构体提示tag
    Mock使用
    Postman文档导出
  • 原文地址:https://www.cnblogs.com/xiaohunshi/p/5706222.html
Copyright © 2011-2022 走看看