反转单链表[Java]

反转单链表[Java],java,singly-linked-list,Java,Singly Linked List,我想知道是否有人可以帮助解释如何在不创建新节点或更改现有节点中的数据的情况下反转单个链接列表。我正在努力准备期末考试,我们在上一次考试中遇到了这个问题。他们没有公布测试编码部分的答案,我也没有弄明白 他们告诉我们最好的方法是使用“跑步技术”,我相信我知道这是什么。他们把它描述为使用两个指针或计数器来遍历一个列表并收集信息,但我不知道如何使用它来反转一个单独喜欢的列表。我能够强制代码反转长度为2、3和4的列表,但我无法进行循环或递归。感谢您提供有关如何执行此操作的任何代码或解释。您可以从一个接一个

我想知道是否有人可以帮助解释如何在不创建新节点或更改现有节点中的数据的情况下反转单个链接列表。我正在努力准备期末考试,我们在上一次考试中遇到了这个问题。他们没有公布测试编码部分的答案,我也没有弄明白


他们告诉我们最好的方法是使用“跑步技术”,我相信我知道这是什么。他们把它描述为使用两个指针或计数器来遍历一个列表并收集信息,但我不知道如何使用它来反转一个单独喜欢的列表。我能够强制代码反转长度为2、3和4的列表,但我无法进行循环或递归。感谢您提供有关如何执行此操作的任何代码或解释。

您可以从一个接一个从输入列表中弹出元素并将其推到最初为空的结果列表的想法开始推导代码:

NODE reverse(NODE list) {
  NODE result = null;
  while (list != null) {
    NODE head = <pop the first node off list>
    <push head onto result>
  }
  return result;
}

您已经完成了…

这取决于您对列表的实现,但我将递归到末尾,然后反转引用

void Reverse(List pList) {
   Reverse(pList, null, pList.First); // initial call
}

void Reverse(List pList, Node pPrevious, Node pCurrent) {
   if (pCurrent != null)
      Reverse(pList, pCurrent, pCurrent.Next);   // advance to the end

   else { // once we get to the end, make the last element the first element
      pList.First = pPrevious;
      return;
   }

   pCurrent.Next = pPrevious; // reverse the references on all nodes
} 

你应该看看这个问题:非常感谢,这很有帮助。我刚刚意识到这会创建一个新节点,我忘了我们不能这样做。有没有办法改变这一点,这样我就不会创建新节点?@AnthonyRulli没有创建新的
节点
s;对现有节点的引用只是复制到变量中。如果你不能做到这一点,那么即使是最简单的列表也无法做到。@AnthonyRulli你认为这为什么会创建新节点?这需要调用
新节点()
。正如你所看到的,没有这样的电话。
void Reverse(List pList) {
   Reverse(pList, null, pList.First); // initial call
}

void Reverse(List pList, Node pPrevious, Node pCurrent) {
   if (pCurrent != null)
      Reverse(pList, pCurrent, pCurrent.Next);   // advance to the end

   else { // once we get to the end, make the last element the first element
      pList.First = pPrevious;
      return;
   }

   pCurrent.Next = pPrevious; // reverse the references on all nodes
}