java - 帮助了解 Java 中的后向递归和 LinkedList

标签 java recursion linked-list

/**
     * Converts linked list into a sentence (a single string representation).
     * Each word pair is separated by a space. A period (".") is appended after
     * the last word. The last link represents the first word in the sentence
     * (and vice versa). The partialResult is the partial string constructed
     * from earlier links. This partialResult is initially an empty string. 
     */
    public String getReversedSentence(String partialResult) {
        if (next==null) {
            partialResult+=this.word;
            return partialResult + ".";
        }
        else{
            partialResult=next.getReversedSentence(partialResult) + this.word;
            return partialResult;
            }
    }

一切工作正常,除了句点(和空格,但我还不担心这一点)。我无法正确放置句号。

这是失败的测试:

public void testGetReversedSentence() {
        LinkedList tail = new LinkedList("not",null);
        LinkedList middle = new LinkedList("too",tail);
        LinkedList head = new LinkedList("tricky",middle);
        assertEquals("not.",tail.getReversedSentence(""));
        assertEquals("not too tricky.",head.getReversedSentence(""));

它提出了not.tootricy而不是nottootootricky.

编辑:构造函数

public LinkedList(String word, LinkedList next) {
        this.word = word;
        this.next = next;
    }

有什么提示吗?

最佳答案

嗯......没有必要使用 2 个方法,(重要)--> 因为这个方法有 StringpartialResult 作为参数。(如果你可以的话,你可以想要并且解决方案中是否允许辅助方法,但这是不必要的。)换句话说,尝试找到某种方法将当前单词与partialResult合并。另一个提示:有一个 3 行长的解决方案(并且格式正确)。

关于java - 帮助了解 Java 中的后向递归和 LinkedList,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4071340/

相关文章:

java字符串到json元素的转换

c# - 使用基于 Tile 的移动计算所有可能终点的算法

java - 有什么办法可以结合这两种方法吗?

java - 一个接一个地从 Arraylist 中打印出不同的项目

java - 无法在 Maven 设置中引用 Chromedriver.exe 在 Selenium Grid 中运行测试

java - 字符串到本地日期中的月年

c++ - 二叉搜索树。插入方法插入不正确

java - 如何使用用户输入更改对象的名称?

c++ - 从二进制文件中检索数据,无意义的字符