思路:首先查询第一个有效元素(不重复的),然后递归查询。
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
public class Solution {
public ListNode deleteDuplicates(ListNode head) {
head=findFirst(head);
if (head!=null) {
head.next=deleteDuplicates(head.next);
}
return head;
}
public ListNode findFirst(ListNode head) {
if (head==null||head.next==null||head.val!=head.next.val) {
return head;
}
int i=head.val;
while (head!=null) {
if (head.val!=i) {
return findFirst(head);
}
head=head.next;
}
return null;
}
}
耗时:332ms,中游。
本文介绍了一种从单链表中移除所有重复元素的方法,通过递归地找到第一个不重复的节点,并继续处理剩余链表。此算法在332ms内完成,表现处于中等水平。
1040

被折叠的 条评论
为什么被折叠?



