代码:
为了找到结果的head 可以在head前加一个dummy dummy->head 再顺序去重
java
/**
* 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)return head;
// while(head.next!=null&&head.val==head.next.val){
// while(n1!=null&&n1.next!=null&&n1.val==n1.next.val){
// if(n1.next.next!=null){
// head=n1.next.next;
// }else{
// return null;
// }
// n1=n1.next;
// }
// }
if(head.next==null)return head;
ListNode dummy = new ListNode(0,head);
ListNode n1 = dummy;
while(n1.next!=null&&n1.next.next!=null){
ListNode n2 = n1.next;
ListNode n3 = n1.next.next;
if(n2.val==n3.val){
while(n2.val==n3.val){
n2 = n3;
n3 = n3.next;
if(n2==null||n3==null){
n1.next=null;
break;
}else{
n1.next = n3;
}
}
}else{
n1=n1.next;
}
}
return dummy.next;
}
}