示例代码
/**
* 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) {
if(head==null||head.next==null){
return head;
}
ListNode dummy=new ListNode();
dummy.next=head;
ListNode pre=dummy,cur=head;
while(pre.next!=null){
boolean falg=false;
while(cur!=null&&cur.next!=null&&cur.val==cur.next.val){
cur=cur.next;
falg=true;
}
if(!falg){
//如果没有发现重复的话,就自动变为下一个元素
pre=cur;
}else{
//pre相当于没动 不然会有 1,2,2,3,3的情况
pre.next=cur.next;
}
cur=cur.next;
}
return dummy.next;
}
}
效果展示