题目链接:https://leetcode-cn.com/problems/remove-duplicates-from-sorted-list-ii/
题目如下:
/**
* 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 pre_set=new ListNode(0);
pre_set.next=head;
head=pre_set;
int flag=0,val=0;//使用三个指针
ListNode pre=head,cur=head.next,next=head.next.next;
while(next!=null){
if(cur.val==next.val){
flag=1;val=cur.val;
pre.next=cur.next;
cur=cur.next;
next=next.next;
}else{
if(flag==1&&val==cur.val){//删除当前的pre节点
flag=0;
pre.next=cur.next;
}
else pre=pre.next;
cur=cur.next;
next=next.next;
}
}
if(flag==1&&val==cur.val) pre.next=cur.next;
return head.next;
}
}