我需要返回链接列表的头部,并删除所有重复的元素。我理解问题的逻辑,但是我在使用递归时感到困惑。删除链接列表中的重复值(Java中的递归)
/*
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'。
我真的很想就如何更好地理解递归提出一些建议。
一些细节: - 你不需要在第一个括号中围绕这两个术语,因为('=='在'||'之前)[https://docs.oracle.com/javase/tutorial/的java/nutsandbolts/operators.html]。 - 按照惯例,Java中的方法没有大写,即在这种情况下它应该被命名为'removeDuplicates'。 –