Remove duplicates in a sorted linked list

June 23, 2022 · 1 min read

https://leetcode.com/problems/remove-duplicates-from-sorted-list/

Check for last element having duplicate

class Solution {
public:
  ListNode *deleteDuplicates(ListNode *head) {
    ListNode *tmp = head, *prev = head;

    while (tmp != nullptr) {
      if (tmp->val != prev->val) {
        prev->next = tmp;
        prev = tmp;
      }
      tmp = tmp->next;
    }

    if (prev != tmp)
      prev->next = nullptr;

    return head;
  }
};
Find the starting point of the loop
Remove duplicates in a unsorted linked list