C/C++;递归可逆链表的Java翻译
我试图用Java递归地反转一个单链表,我从斯坦福大学的代码中学到了这一点。有人能帮我把C/C++代码翻译成java,这样我的RecursiveVerse()仍然是一个无效的方法吗 以下是斯坦福大学的C/C++解决方案:C/C++;递归可逆链表的Java翻译,java,c++,c,recursion,Java,C++,C,Recursion,我试图用Java递归地反转一个单链表,我从斯坦福大学的代码中学到了这一点。有人能帮我把C/C++代码翻译成java,这样我的RecursiveVerse()仍然是一个无效的方法吗 以下是斯坦福大学的C/C++解决方案: void RecursiveReverse(struct node** headRef) { struct node* first; struct node* rest; if (*headRef == NULL) return; first
void RecursiveReverse(struct node** headRef) {
struct node* first;
struct node* rest;
if (*headRef == NULL) return;
first = *headRef;
rest = first->next;
if (rest == NULL) return;
RecursiveReverse(&rest);
first->next->next = first;
first->next = NULL;
*headRef = rest;
}
下面是我对代码翻译的尝试:
public void recursiveReverse(Element<T> currElement) {
Element<T> first;
Element<T> rest;
if (currElement == null) return;
first = currElement;
rest = currElement.next;
if (rest == null) return;
recursiveReverse(rest);
first.next.next = first;
first.next = null;
head = rest;
public void recursiverse(元素currenelement){
元素优先;
元素休息;
if(currElement==null)返回;
第一个=当前元素;
rest=current.next;
if(rest==null)返回;
递归翻转(休息);
first.next.next=first;
first.next=null;
头=休息;
}
我最初使用“currElement=rest”作为最后一行,但是当我开始使用1,2,3,null时,得到的输出是1,null
但是在使用head=rest(linkedlist的原始head)之后,我现在有了2,1,null
有人能帮我翻译正确,这样我就可以得到输出为3,2,1,空?任何帮助都将不胜感激
谢谢 Java通过值传递,而C代码(不是C++)通过引用(指向指针的指针)传递。因此,这两种实现不同。请看< p> C++的精确性是混叠,改变传递的变量。在这里,使用函数结果可以达到相同的效果
public Element<T> recursiveReverse(Element<T> currElement) {
if (currElement == null) return null;
Element<T> rest = currElement.next;
if (rest == null) return currElement;
Element<T> reversed = recursiveReverse(rest);
rest.next = currElement;
currElement.next = null;
return reversed;
}
公共元素递归变量(元素currenelement){
if(currElement==null)返回null;
元素rest=currenelement.next;
if(rest==null)返回current元素;
元素反转=递归反转(剩余);
rest.next=current元素;
currElement.next=null;
反向返回;
}
在java中,通常在第一次使用时声明。我发现
rest.next
比first.next.next
更清晰。谢谢你,乔普,你的解决方案非常有效。但是,让方法在每次调用时都不返回元素的情况下更改元素的链接(从而重新排列它们)是完全不可能的吗?如果是这样的话,这是否与通过引用传递有关(谢谢,迪特!)?我在想,因为我们在内存中有这些元素,我们可以在访问它们后更改它们的链接。使用反向列表,您需要返回最后一个链接,而这只能在递归调用之后完成,作为out参数或返回值。在java中,这样一个out参数可以作为一个元素的数组:void recursiverse(element[]ref)
。