Another Java solution using "fast" + "slow" pointers, O(n) 1ms


  • 0
    G
    public class Solution {
        public ListNode deleteDuplicates(ListNode head) {
            if (head == null) return null;
            ListNode dummy = new ListNode(0);
            ListNode slow, fast;
            slow = dummy;
            while (head != null) {
                fast = head.next;
                while ((fast != null) && (fast.val == head.val)) fast = fast.next;
                if (head.next == fast) {
                    slow.next = head;
                    slow = slow.next;
                    slow.next = null;
                }
                head = fast;
            }
            return dummy.next;
        }
    }

Log in to reply
 

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