通过万岁!!!
java代码
class Solution {
public ListNode deleteDuplicates(ListNode head) {
if (head == null || head.next == null) {
return head;
}
ListNode l = head, result = head;
boolean repeat = false, repeatHead = false; // repeat记录l是不是重复的,repeatHead记录最开始head是不是重复
if (head.next.val == head.val) {
repeat = true;
repeatHead = true;
}
head = head.next;
while (head.next != null) {
if (head.next.val == head.val) {// 重复了需要删除的下一个节点
repeat = true;// 标记l节点也要删除
head.next = head.next.next; // 先删除下面的节点
} else {
if (repeat) {// l是重复的
l.next = head.next;
head = l.next;
repeat = false;
continue;
}
head = head.next;
l = l.next;
}
}
if (repeat)
l.next = null;
if (repeatHead)
return result.next;
return result;
}
}