Remove Duplicates from Sorted List

Given a sorted linked list, delete all duplicates such that each element appear only once.

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

public class Solution {
    public ListNode deleteDuplicates(ListNode A) {
        if (A == null)
            return A;
        ListNode temp1 = A;
        while (temp1 != null) {
            ListNode temp2 = temp1;
            while (temp2 != null && temp1.val == temp2.val)
                temp2 = temp2.next;
            temp1.next = temp2;
            temp1=temp1.next;
        }
        return A;
    }
}

Last updated