【发布时间】:2016-11-23 07:55:02
【问题描述】:
我需要返回链表的头部,删除所有重复的元素。我理解问题的逻辑,但我对使用递归感到困惑。
/*
Node is defined as
class Node {
int data;
Node next;
}
*/
Node RemoveDuplicates(Node head) {
if ((head == null) || (head.next == null))
return head;
else {
RemoveDuplicates(head.next);
if (head.data==head.next.data) head.next = head.next.next;
}
return head;
}
如果我在 if 条件之前调用函数 RemoveDuplicates(head.next);它工作正常。但是,如果我交换语句的顺序(其余一切都完全相同),例如:
if (head.data==head.next.data) head.next = head.next.next;
RemoveDuplicates(head.next);
代码无法正确解决像“1->1->1->1”这样的测试用例。我在后一种情况下得到的输出是'1->1'。
我真的想要一些关于如何更好地理解递归的建议。
【问题讨论】:
-
一些细节: - 第一个 if 中的两个术语不需要括号,因为 (
==在||之前)[docs.oracle.com/javase/tutorial/java/nutsandbolts/…。 - 按照惯例,Java 中的方法不大写,即在这种情况下应将其命名为removeDuplicates。
标签: java recursion linked-list