Skip to content

Instantly share code, notes, and snippets.

@si-yao
Created September 12, 2019 06:28
Show Gist options
  • Save si-yao/435518b60ebc5620ca20af1219177b57 to your computer and use it in GitHub Desktop.
Save si-yao/435518b60ebc5620ca20af1219177b57 to your computer and use it in GitHub Desktop.
/**
* 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