简体   繁体   English

使用递归反向打印单链接列表-Java

[英]Print Singly linked list in reverse using recursion - Java

Hi I am having a little trouble trying to print a singly linked list in reverse order using recursion. 嗨,我在尝试使用递归以相反的顺序打印单链接列表时遇到了一些麻烦。 I have looked at some examples but my method doesn't take any parameters. 我看了一些示例,但是我的方法没有任何参数。 I want to print it out in the following format: 我想以以下格式打印出来:

input: [1, 2, 3, 4, 5] and output:[5, 4, 3, 2, 1]

first refers to to first node in my singly linked list and I use StringBuilder to build up my list so I can return it at the end. 首先是指单链接列表中的第一个节点,我使用StringBuilder来构建列表,以便最终将其返回。

This is what I have so far: 这是我到目前为止的内容:

public String printReverse() {
    StringBuilder myString = new StringBuilder("[");
    if (head != null) { // base case
        head = head.next;
        myString.append(head.value);   // line 406
        myString.append(", ");         // line 407
        printReverse();                // line 408
    }
    myString = myString.append("]");
    return myString.toString();
}

I get the following error: 我收到以下错误:

Exception in thread "main" java.lang.NullPointerException
    at myprog.SLL$Node.access$100(SLL.java:445)

    at myprog.SLL.printReverse(SLL.java:406)

    at myprog.SLL.printReverse(SLL.java:408)

    at myprog.SLL.printReverse(SLL.java:408)

    at myprog.SLL.printReverse(SLL.java:408)

    at myprog.SLL.printReverse(SLL.java:408)

    at myprog.SLLApp.myMethod(SLLApp.java:198)

    at myprog.SLLApp.<init>(SLLApp.java:37)

    at myprog.SLLApp.main(SLLApp.java:26)

I don't see what I am doing wrong, but I suspect it may be the way I call the method on itself. 我看不到我在做什么错,但是我怀疑这可能是我自己调用该方法的方式。 Can anyone suggest what I may be doing wrong and how I may go about fixing it? 谁能建议我可能做错了什么以及如何解决?

Thanks! 谢谢!

You are over complicating things. 您正在使事情复杂化。 Lets look at the pseudo code: 让我们看一下伪代码:

  • initial node is head 初始节点是头
  • if next is null print blank (recursion termination condition) 如果next为null,则打印空白(递归终止条件)
  • else recurse to next node 否则递归到下一个节点
  • then print current node 然后打印当前节点

In code, this becomes: 在代码中,这变为:

public String printReverse() {
    return printReverse(head); 
}

private String printReverse(Node n) {
    return next == null ? "" : (printReverse(next) + n.value);
}

It's really only two lines of code - see KISS . 实际上只有两行代码-参见KISS

Regarding the second private method, it is very common for the public method of a recursive implementation to just set ip the call to a private recursive method with the appropriate initial state. 关于第二个私有方法,对于递归实现的公共方法来说,仅将调用设置为具有适当初始状态的私有递归方法是很常见的。

You can't declare the result variable inside the method. 您不能在方法内部声明结果变量。 You can have it as parameter to a private helper method though. 不过,您可以将其作为私有帮助器方法的参数。 Here is a sample implementation: 这是一个示例实现:

public String printReverse(Elem elem) {
    return internalReverse(elem, new StringBuilder("[")).append("]").toString();
}
private StringBuilder internalReverse(Elem elem, StringBuilder result) {
    if (elem != null) { // base case
        result.append(internalReverse(elem.next, result));                
        if (result.size() > 1) {
            result.append(", ")
        }            
        result.append(elem);
    }
    return result;
}

A Javascript solution. Javascript解决方案。

function printReverse(list) {
    if (!list) return;
    if (list.next) {
        printReverse(list.next);  
    }
    console.log(list.value);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM