Leetcode: Remove Duplicates from Sorted List

This question is a Leetcode easy, but it is asked at Amazon, Adobe, Goldman Sachs, and Qualcomm: 

Given the head of a sorted linked list delete all duplicates such that each element appears only once. Here are the deletions:


So we go over the linked list and set the next element to next = next.next if element and iterate. It's pretty simple. Here's the code: 

class Solution {

    public ListNode deleteDuplicates(ListNode head) {

        ListNode current = head;

        while(current != null && current.next != null) {

            if(current.val == current.next.val) {

                //if 2 duplicates, remove the duplicate by resetting the linked list pointer

                current.next - current.next.next;

            } else {

                //else don't change anything

                current = current.next;

            }

        }

        return head;

    }

}

Comments

Popular Posts