简体   繁体   English

用于反转链表的递归代码无法正常工作

[英]Recursive code for reversing a linked list is not working properly

Here tail is a pointer to the last element of linked list.这里的tail是指向链表最后一个元素的指针。 This code only works when there are odd numbers of nodes in a linked list and shows wrong output for even number of nodes.此代码仅在链表中有奇数个节点时有效,并且显示偶数个节点的错误输出。 Please help what is the problem in the code and reason why it is happening?请帮助代码中的问题是什么以及它发生的原因?

 public static class Node
 {
    int data;
    Node next;
  }

  public static class LinkedList
  {
    Node head;
    Node tail;
    int size;
    // many other member functions
    
    private void reversePRHelper(Node node , Node prev)
    {
      if(node == null)
      {
        return;
      }
      Node Next = node.next;
      node.next = prev;
      prev = node;
      reversePRHelper(Next , prev);
      
      Node temp = this.head;
      this.head = this.tail;
      this.tail = temp;
      
    }
    public void reversePR()
    {
      reversePRHelper(head,null);
    }
}
  

The bug in your code is that these three lines:您代码中的错误是这三行:

Node temp = this.head;
this.head = this.tail;
this.tail = temp;

should only be executed once, at the end, and not for each recursive call.应该只在最后执行一次,而不是每次递归调用。 So if you move those three statements out of your reversePrHelper method and into your reversePR method, your code will work.因此,如果您将这三个语句从您的 reversePrHelper 方法中移到您的 reversePR 方法中,您的代码将起作用。

private void reversePRHelper(Node node , Node prev)
{
  if(node != null)
  {
   return;
  }
  Node Next = node.next;
  node.next = prev;
  prev = node;
  reversePRHelper(Next , prev);
}

public void reversePR()
{
  reversePRHelper(head,null);
  Node temp = this.head;
  this.head = this.tail;
  this.tail = temp;
}

For me it is unclear however why you keep the tail as an attribute, since you can't navigate anywhere from the tail, as it has no next value.对我来说,尚不清楚为什么将尾部保留为属性,因为您无法从尾部导航到任何地方,因为它没有下一个值。 It would be different if your nodes would keep a reference to the previous element as well, but then it would be a double linked list.如果您的节点也保留对前一个元素的引用,则情况会有所不同,但它将是一个双向链表。

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

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