/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public ListNode deleteDuplicates(ListNode head) {
ListNode pre = null;
ListNode current = head;
while(current != null){
int val = current.val;
ListNode cur = current;
current = current.next;
int num = 0;
while(current != null && current.val == val){//遍历所有的重复元素
num++;
current = current.next;
}
if(num == 0){//没有重复的元素
pre = cur;
}else{//有重复的元素
if(pre == null){//重复元素是头结点
head = current;
}else{//重复元素不在头结点
pre.next = current;
}
}
}
return head;
}
}
原文:https://www.cnblogs.com/GarrettWale/p/14608165.html