/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
public ListNode deleteDuplicates(ListNode head) {
// Start typing your Java solution below
// DO NOT write main() function
if(head==null)return null;
if(head.next==null)return head;
ListNode sen = new ListNode(-1);
sen.next = head;
ListNode cur = head;
ListNode pre = sen;
int val = cur.val;
boolean b = false;
while(cur.next!=null){
if(cur.next.val!=val){
if(b==false){
pre = cur;
cur = cur.next;
val = cur.val;
}
else{
b=false;
pre.next = cur.next;
val = pre.next.val;
cur = pre.next;
}
}
else{
cur = cur.next;
b = true;
}
}
if(cur.val==val&&b==true){pre.next = null;}
return sen.next;
}
}
有点绕,
设置一个开始哨兵节点。
设置pre , cur
选一个开关标示是否重复。