My concise Java solution


  • 0
    S
    public class Solution {
        public ListNode deleteDuplicates(ListNode head) {
            if(head == null)
                return head;
            
            ListNode dummy = new ListNode(0); //fake head
            ListNode newHead = dummy;
            
            while(head != null){
                if(head.next == null || head.val != head.next.val){   //add after dummy
                    dummy.next = head;
                    dummy = dummy.next;
                    head = head.next;
                }else{
                    int val = head.val;
                    while(head != null && head.val == val)  //ensure the node is distinct
                        head = head.next;
                }
            }
            dummy.next = null;
            
            return newHead.next;
        }
    }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.