remove duplicates from sorted list leetcode solution in c++

Here is a solution in C++ to remove duplicates from a sorted list on LeetCode:

ListNode deleteDuplicates(ListNode head) {
    if (head == nullptr) {
        return nullptr;
    }

    ListNode* current = head;

    while (current->next != nullptr) {
        if (current->val == current->next->val) {
            ListNode* temp = current->next;
            current->next = current->next->next;
            delete temp;
        } else {
            current = current->next;
        }
    }

    return head;
}

Explanation for each step:

  1. The function deleteDuplicates takes a pointer to the head of the sorted list as its input parameter and returns a pointer to the head of the modified list.

  2. We first check if the list is empty by comparing the head pointer to nullptr. If it is, we return nullptr indicating an empty list.

  3. We initialize a pointer current to the head of the list. This pointer will be used to traverse the list and remove duplicates.

  4. We enter a loop that continues until current->next is nullptr, i.e., until we reach the end of the list.

  5. Inside the loop, we compare the value of the current node current with the value of its next node current->next. If they are equal, it means we have found a duplicate.

  6. To remove the duplicate, we first store the pointer to the next node in a temporary pointer temp.

  7. We update the current->next pointer to skip the duplicate node by setting it to current->next->next.

  8. We delete the duplicate node using the delete keyword to free the memory allocated for it.

  9. If the values of the current node and its next node are not equal, we move the current pointer to the next node by setting it to current->next.

  10. Once the loop ends, we have removed all duplicates from the list, and we return the modified list by returning the head pointer.

This solution uses a two-pointer approach to remove duplicates in a sorted list. The time complexity of this solution is O(n), where n is the number of nodes in the list, as we traverse the list once to remove duplicates.