Simple Java Approach.


  • 1
    S

    The idea is to keep traversing till we get duplicates.
    e.g
    1-2-2-2-3

    Suppose iterator (p) is at Node 1.
    Now t knows that 2 is repeated ahead. So it will keep jumping over nodes,
    till the next element is '2'.

    /**
     * Definition for singly-linked list.
     * public class ListNode {
     *     int val;
     *     ListNode next;
     *     ListNode(int x) { val = x; }
     * }
     */
    public class Solution {
        public ListNode deleteDuplicates(ListNode head) {
            ListNode dummyHead = new ListNode(0);
            dummyHead.next = head;
            ListNode p = dummyHead;
            while (p != null) {
                if (p.next != null && p.next.next != null && p.next.val == p.next.next.val) {
                    int val = p.next.val;
                    while (p.next != null && p.next.val == val) {
                        p.next = p.next.next;
                    }
                } else {
                    p = p.next;
                }
            }
            return dummyHead.next;
        }
    }
    

Log in to reply
 

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