java - 用于反转链表的递归代码无法正常工作
问题描述
这里的tail是指向链表最后一个元素的指针。此代码仅在链表中有奇数个节点并显示偶数个节点的错误输出时才有效。请帮助代码中的问题是什么以及它发生的原因?
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);
}
}
解决方案
您的代码中的错误是这三行:
Node temp = this.head;
this.head = this.tail;
this.tail = temp;
应该只在最后执行一次,而不是每次递归调用。因此,如果您将这三个语句从您的 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;
}
对我来说,不清楚为什么要将尾部保留为属性,因为您无法从尾部导航到任何地方,因为它没有下一个值。如果您的节点也保留对前一个元素的引用,那将是不同的,但它将是一个双链表。
推荐阅读
- reactjs - Formik 字段包装器
- javascript - Javascript,编写 if 条件的更好方法
- javascript - 使用相同的表格添加和更新
- kotlin - 如何替换阻塞代码以在 Kotlin 中读取字节
- python - 将 f-string 语法转换为在旧版本的 python 中打印
- swift - 如何在单个 ViewController 中设置多个 UITableview
- r - 抓取 Fox News 网站时的空标题节点
- flutter - 尝试显示 Flutter 快餐栏会引发异常错误
- apache-spark - 如何将 spark-dataframe 包装到根元素?
- r - 如何使用修改后的回归创建汇总表?