题目传送地址:https://leetcode.cn/problems/remove-duplicates-from-sorted-list-ii/
运行效率
代码如下:
//递归解法
class Solution {
public static ListNode deleteDuplicates(ListNode head) {
//处理边界情况
if (head == null || head.next == null) {
return head;
}
int nextVal = head.next.val;
ListNode listNode = deleteDuplicates(head.next);
//处理特殊情况
if(listNode==null){
//比如head=[3,3,3]这种情况
if(nextVal== head.val){
return null;
}
//比如head={1,2,2}
head.next=null;
return head;
}
//比如这种情况[1,1,1,2,3] head.val=1 head.next=[1,1,2,3] , 这个时候返回的listNode=[2,3]
if (head.val == nextVal && listNode.val != nextVal) {
return listNode;
}
if (head.val == listNode.val) {
return listNode.next;
} else {
head.next = listNode;
return head;
}
}
}