【问题标题】:Reverse a singly linked list in Java反转Java中的单链表
【发布时间】:2018-01-06 22:22:03
【问题描述】:

我正在尝试反转一个链表并返回新的头部。

public Node reverse(Node head) {
    Node node = head;
    if (node.next == null) {
        head = node;
        return head;
    }
    Node next = node.next;
    reverse(next);
    next.next = node;

    return head;
}

节点类:

public class Node {
    int data;
    Node next;
}

输入 1 -> 2 -> 3 -> 4 -> 5 我得到输出 1 -> 2 -> 1 -> 2 -> 1。为什么它会循环通过前 2 个节点而忽略剩余的 3 ?还有,为什么新的head没有更新到节点5?

【问题讨论】:

  • take the tour 了解该网站的运作方式以及此处的主题有哪些问题,并edit 相应地提出您的问题。另见:How to Debug Small Programs
  • 我认为,如果您将列表推入堆栈,然后从堆栈的头部创建一个新列表(或清除旧列表),它也会反转该列表。可能不节省空间,但易于编码和维护。

标签: java linked-list


【解决方案1】:

有2个问题:

  1. 一旦返回新的head(当您到达列表末尾时),您就不会保存它,因此返回的head 始终是第一个递归堆栈,即原来的第一个节点;
  2. 您没有将node.next 分配给第一个节点上的null,因此它永远不会成为列表的新尾部。

这是更正后的代码:

public Node reverse(Node head) {
    Node node = head;
    if (node.next == null) {
        head = node;
        return head;
    }
    Node next = node.next;

    // fix for problem 2, we transform the current node in the tail
    node.next = null;

    // fix for problem 1, head is now the tail node
    head = reverse(next);   

    next.next = node;

    return head;
}

【讨论】:

    猜你喜欢
    • 2018-10-16
    • 1970-01-01
    • 1970-01-01
    • 2014-12-30
    • 2016-09-29
    • 1970-01-01
    • 2016-06-07
    相关资源
    最近更新 更多