Remove Duplicatesfrom Sorted List I I Algorithm

The Remove Duplicates from Sorted List II Algorithm is an efficient technique used to eliminate all the duplicate elements in a sorted linked list, leaving only distinct elements. It is particularly helpful in situations where maintaining a list with unique elements is crucial for the functionality of the system. This algorithm works on the basic principle of traversing the sorted linked list while comparing the current node's value with the next node's value. If the values are the same, it indicates the presence of duplicate elements, and the algorithm proceeds to remove all occurrences of the duplicate element. Otherwise, it moves on to the next node until the entire list is traversed and all duplicates are removed. To implement the Remove Duplicates from Sorted List II Algorithm, a dummy node is created to serve as the new head of the modified list. This dummy node helps in simplifying edge cases, such as when the actual head of the list needs to be removed due to duplication. Two pointers, 'prev' and 'curr', are initialized to keep track of the previous and current nodes during traversal. The algorithm iterates through the list, and if the current node's value is equal to the next node's value, it continues traversing until it finds a distinct value or reaches the end of the list. Once a distinct value is found, the 'prev' pointer's next value is updated to point to this distinct node, effectively removing all duplicates. If no duplicate is found, the 'prev' pointer is simply moved to the current node. This process is repeated until the entire list is traversed, and the modified list with only distinct elements is obtained.
/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode *deleteDuplicates(ListNode *head) {
        ListNode prevhead(0);
        ListNode* prev = &prevhead;
        ListNode* curr = head;
        while (curr) {
            if (curr->next && curr->val == curr->next->val) {
                ListNode* next = curr->next;
                while (next && next->val == curr->val) {
                    next = next->next;
                }
                curr = next;
            } else {
                prev->next = curr;
                prev = prev->next;
                curr = curr->next;
            }
        }
        prev->next = NULL;
        return prevhead.next;
    }
};

LANGUAGE:

DARK MODE: