# Remove duplicates from a linked list

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

For example:

• Given 1->1->2, return 1->2.
• Given 1->1->2->3->3, return 1->2->3.

The following is my code:

struct ListNode {
int data;
ListNode *next;
ListNode(int x) : data(x), next(NULL) {}
};

}

}

// Start typing your C/C++ solution below
// DO NOT write int main() function
ListNode *next = NULL;
while (cur != NULL){
next = getNextElement(cur);
cur->next = next;
cur = next;
}
}
• Are the nodes dynamically allocated. If so you are leaking. Commented Mar 9, 2013 at 18:48
• yes, I don't write code to free dynamically allocated memory~ Commented Mar 9, 2013 at 19:40
• Do the duplicates occur in quick succession or they can randomly be anywhere in the list? Commented Dec 29, 2014 at 14:36
• @Fihop Hey, I really like the simplicity of your solution. Is it possible to do this recursively instead of using a while loop? I've tried a couple varieties but they all mess up with edge cases. Commented Sep 20, 2017 at 12:04

while ((head != NULL)                      // This can't be NULL
// because you test before calling.
}

// If head can be NULL then you should also be checking here.
// Otherwise this may fail.
}

Small notes:

// Start typing your C/C++ solution below
// DO NOT write int main() function

// Replace with for(;;)
for(ListNode* cur = head; cur != NULL; cur = cur->next){
// Move declaration of next here.
// It is not used outside the loop so why pollute
ListNode *next = getNextElement(cur);

// May want to make sure you don't leak.
ListNode *old  = cur->next;
while(old != next)
{
ListNode* toFree = old;  // you can probably put this logic in getNext()
old = old->next;
free(toFree);
}
cur->next = next;
}