通过递归反转单个链表

时间:2018-09-29 12:08:51

标签: java recursion singly-linked-list

这是用于通过递归逆转单个链表的代码:

public static LinkedListNode reverse_recursive(
      LinkedListNode head) {

    if (head == null || 
        head.next == null) {
        return head;
    }

    LinkedListNode reversed_list = 
      reverse_recursive(head.next);

    head.next.next = head;
    head.next = null;
    return reversed_list;
  }

我知道递归不是解决此问题的最佳方法,但是我无法弄清楚代码“ head.next.next = head”的作用。我很困惑,请帮助我清除思路。谢谢!

3 个答案:

答案 0 :(得分:0)

head --> A
         .next --> B
                   .next --> C

因此,在以上示例中,head.next引用了节点B,head.next.next引用了节点C。

head.next.next = something
因此

等于

nodeB.next = something

在您的代码中,somethingheadhead引用了节点A。因此,它为节点B的下一个节点分配了一个新值,如果节点A:则分配了该新值:

head --> A <---------------
         .next --> B      |
                   .next --

以下说明是

head.next = null, which thus leads to

head --> A <---------------
                   B      |
                   .next --

答案 1 :(得分:0)

head.next.next = head 

正在将当前节点(头)分配为递归上次访问的节点的链接。

递归将从列表中的最后一个节点开始,并在第一个节点上结束。

假设您具有链接列表A --> B --> C --> D --> NULL

它将开始从node D反转上述列表,并且由于节点D的nextnull,因此递归将立即移至下一个节点node C < / p>

将会发生的事情是抢占先机(现在为node C),并将其分配为node D的{​​{1}}

这将一直发生,直到不再有要遍历的节点为止

enter image description here

答案 2 :(得分:0)

public static LinkedListNode reverse_recursive(LinkedListNode head) {
if (head == null || head.next == null) {
    return head;
}

如果节点(在本例中为head)等于null或下一个节点等于null (意味着只有一个节点),然后返回该节点,因为您无法反转空引用或仅包含一个节点的列表(基本上已经被反转)。这是递归解决方案的基本情况。

LinkedListNode reversed_list = reverse_recursive(head.next);

我们将下一个节点发送到递归函数中,例如如果我们的列表具有三个节点1-> 2-> 3,那么我们将把第二个节点发送到reverse_recursive函数中。该函数将返回3-> 2,reversed_list将指向节点3。现在,我们需要将节点1连接到反向列表3-> 2。

head.next.next = head;

head.next(节点2)将指向(head.next.next)节点1(头部)。

head.next = null;

由于节点1是最后一个节点,因此它应指向null,这意味着不再有节点。

return reversed_list;

现在我们只需要返回正确的引用(反向列表的第一个节点)。