写在前面:
删除链表中重复的结点,我们需要考虑两种重复的情况:
(1)从head就开始重复 eg:{1,1,2,2,3}
(2)正常重复 eg:{1,2,2,3,3,5}
那么为了避免第一种情况出现,程序没有删除头结点,我们需要自己创建一个头结点:
ListNode first = new ListNode(-1);// 新建一个头节点,避免,从head就开始重复
此外,我们还要用一个start结点,来记录重复结点出现之前的结点,比如,第二种情况中,start就记录结点1,最后再将结点5赋值给start.next。
代码实现:
public ListNode deleteDuplication(ListNode head) {
ListNode first = new ListNode(-1);// 新建一个头节点,避免,从head就开始重复
first.next = head;
ListNode current = head;
ListNode start = first; // 保存重复节点的前一个节点
while (current != null && current.next != null) {
if (current.val == current.next.val) {
int value = current.val;
while (current != null && current.val == value) {
current = current.next;
}
start.next = current;
} else {
start = current;
current = current.next;
}
}
// 注意要返回first.next,避免从head就开始重复,而head被删除
return first.next;
}