Created
September 12, 2019 06:28
-
-
Save si-yao/435518b60ebc5620ca20af1219177b57 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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) { | |
if(head==null||head.next==null) return head; | |
ListNode iter = head; | |
head=null; | |
ListNode distinctNode = null; | |
ListNode prev = iter; | |
boolean prevIsDu = false;//prev node is duplicate | |
iter = iter.next; | |
while(iter!=null){ | |
if(iter.val!=prev.val){ | |
if(prevIsDu) | |
prevIsDu=false; | |
else if(distinctNode==null){ | |
distinctNode=prev; | |
head=distinctNode; | |
} | |
else{ | |
distinctNode.next=prev; | |
distinctNode=distinctNode.next; | |
} | |
prev=iter; | |
} | |
else prevIsDu=true; | |
iter=iter.next; | |
} | |
if(!prevIsDu) { | |
if(distinctNode==null){ | |
distinctNode=prev; | |
head=distinctNode; | |
} | |
else{ | |
distinctNode.next=prev; | |
distinctNode=distinctNode.next; | |
} | |
} | |
if(distinctNode!=null) | |
distinctNode.next=null; | |
return head; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment