【问题标题】:Printing Reversed Linked List Using Recursion使用递归打印反向链表
【发布时间】:2021-11-30 20:56:10
【问题描述】:

我试图以相反的顺序打印一个链表,但实际上没有使用递归来反转它,但我的输出结果很奇怪。似乎我的代码基本上选择了第一个节点并在打印完链表的其余部分(按原始顺序)后打印它。我写的代码(据我所见)是正确的,并且与互联网上解决此问题的代码相匹配。

这是我的代码:

public class PrintLinkedListRecursively {

public static void printReverse(Node<Integer> temp) {
    if(temp == null) {
        return;
    }
    
    print(temp.next);
    System.out.print(temp.data);
    
}

public static Node<Integer> input() {
    Scanner scn = new Scanner(System.in);
    int data = scn.nextInt();
    Node<Integer> head = null, tail = null;
    
    while(data!=-1) {
        Node<Integer> currentNode = new Node<Integer>(data);
        if(head == null) {
            head = currentNode;
            tail = currentNode;
        }else {
            tail.next = currentNode;
            tail = tail.next;
        }
        
        data = scn.nextInt();
    }
    
    return head;
    
}

public static void main(String[] args) {        
    Node<Integer> head = input();
    printReverse(head);

}
}

这是 Node 类:

public class Node<T> {

T data;
Node<T> next;

Node(T data){
    this.data = data;
}
}

这是我给出的输入,然后是输出:

1 2 3 4 5 -1
2 3 4 5 1

这里发生的另一件奇怪的事情是,如果我改变退出递归的条件,说如果我这样做:

if(temp.next.next.next == null){
   return;
}

然后是原始代码的其余部分,它实际上仍然给我相同的输出。知道我哪里出错了吗?

【问题讨论】:

  • printReverse方法中,你应该调用printReverse(temp.next)而不是print(temp.next)
  • 小心temp.next.next.next == null 之类的条件 - 这很脆弱(您已经可以为 temp.next.next 中的所有内容获得 NPE,如果列表中的元素少于 3 个等怎么办?) ,难以理解(例如,为什么要 3x next?)而且可能没有必要。
  • 我投票结束这个错误,因为 Asker 认为他们会递归,但他们没有:他们调用了错误的函数。

标签: java recursion linked-list


【解决方案1】:

尝试将printReverse()函数重写为:

public static void printReverse(Node<Integer> temp) {
    if(temp == null) {
        return;
    }
    printReverse(temp.next);
    System.out.print(temp.data);
}

【讨论】:

    猜你喜欢
    • 2013-06-02
    • 1970-01-01
    • 2014-11-27
    • 2020-01-22
    • 2021-06-06
    • 2013-12-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多