LeetCode – Remove Duplicates from Sorted List II (Java)

Given a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinct numbers from the original list.

For example, given 1->1->1->2->3, return 2->3.

Java Solution

public ListNode deleteDuplicates(ListNode head) {
    ListNode t = new ListNode(0);
    t.next = head;
 
    ListNode p = t;
    while(p.next!=null&&p.next.next!=null){
        if(p.next.val == p.next.next.val){
            int dup = p.next.val;
            while(p.next!=null&&p.next.val==dup){
                p.next = p.next.next;
            }
        }else{
            p=p.next;
        }
 
    }
 
    return t.next;
}

4 thoughts on “LeetCode – Remove Duplicates from Sorted List II (Java)”


  1. public ListNode removeDuplicate(ListNode head)
    {
    var previous = head;
    var p = head.next;
    var newHead = null;

    while ( p != null )
    {
    if( p.val == previous.val )
    {
    p = p.next;
    }
    else
    {
    previous = p;
    p = p.next;
    if ( p.val != previous.val && newHead == null )
    {
    newHead = previous;
    }
    }
    }

    return newHead;
    }

  2. There is bug in here. This just removes even number of nodes. Try example:
    1->1->1->2->3 and it fails.

    Fix do if (previous.data == current.data) in a while loop .

  3. public ListNode removeduplicate(ListNode head) {

    if (head == null || head.next == null)
    return head;

    ListNode previous = head;
    ListNode current = head.next;
    ListNode tmp;

    while (current != null) {
    tmp = current.next;
    if (previous.data == current.data) {
    if (previous == head) {
    head = tmp;
    }
    previous = tmp;
    current = tmp.next;
    } else {
    previous = current;
    current = tmp;
    }
    }

    return head;
    }

Leave a Comment