java solution easy to understand


  • 0
    P
    /**
     * Definition for singly-linked list.
     * public class ListNode {
     *     int val;
     *     ListNode next;
     *     ListNode(int x) { val = x; }
     * }
     */
    class Solution {
        
        public ListNode deleteDuplicates(ListNode head) {
            
        if (head==null){return null;}
            
            ListNode prev = new ListNode(-1);
            ListNode forw = head;
            ListNode answer = prev;
            
            while (forw.next!=null){
                
                if (forw.val != forw.next.val ){
                    prev.next = forw;
                    prev=prev.next;
                    forw = forw.next; 
                }else if (forw.val == forw.next.val) {
                    
                    int temp = forw.val;
                    while (forw!=null && forw.val==temp){                    
                        forw=forw.next;                    
                    }                                
                }
                if (forw==null){
                    break;
                }
                            
            }
            
            prev.next=forw;
            return answer.next;
        }
    }
    

Log in to reply
 

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