给定一个已排序的链表的头 head ,删除原始链表中所有重复数字的节点,只留下不同的数字 。返回已排序的链表。
示例 1:
输入:head = [1,2,3,3,4,4,5]
输出:[1,2,5]示例 2:
输入:head = [1,1,1,2,3]
输出:[2,3]提示:
链表中节点数目在范围 [0, 300] 内
-100 <= Node.val <= 100
题目数据保证链表已经按升序排列来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/remove-duplicates-from-sorted-list-ii
class Solution {
public ListNode deleteDuplicates(ListNode head) {
if(head == null || head.next == null) return head;
if(head.val == head.next.val ) {
//如果舍去后 接下来依旧有其他相同的,同样遍历舍去(像3,3,4,4 这样,第一次把3舍去后,会发现4也是有重复的,所以接着遍历舍去4.......)
while(head != null && head.next !=null && head.val == head.next.val){
//相同的舍去
while(head.next != null && head.val == head.next.val)
head = head.next;
//此时head指向的重复的最后一个,同样舍去,指向下一个
head = head.next;
}
}
if(head == null) return head;
//判断后面是否还有重复的
head.next = deleteDuplicates(head.next);
return head;
}
}