0
点赞
收藏
分享

微信扫一扫

Leetcode82. 删除排序链表中的重复元素 II


题目传送地址:​​https://leetcode.cn/problems/remove-duplicates-from-sorted-list-ii/​​

运行效率

Leetcode82. 删除排序链表中的重复元素 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;
}
}

}


举报

相关推荐

0 条评论