my Java O(n) solution


  • 0
    G

    use a boolean variable to avoid nested loop.

    public class Solution {
        public ListNode deleteDuplicates(ListNode head) {
            if(head==null||head.next ==null) return head;
            ListNode dummy = new ListNode(-1);
            dummy.next = head;
            ListNode slow = dummy, fast = dummy.next;
            boolean duplicateDetected = false;
            while((slow.next!=null&&fast.next!=null)||duplicateDetected == true){
                if(slow.next!=null&&fast.next!=null && (slow.next.val==fast.next.val)){
                    fast = fast.next;
                    duplicateDetected =true;
                }else if(duplicateDetected == true){
                    if(slow.next==head) head = fast.next;
                    slow.next = fast.next;
                    fast = fast.next;
                    duplicateDetected = false;
                }else{
                    slow = slow.next;
                    fast = fast.next;
                }
            }
            return dummy.next;
        }
    }
    

Log in to reply
 

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