Given a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinct numbers from the original list.
For example, Given 1->2->3->3->4->4->5, return 1->2->5. Given 1->1->1->2->3, return 2->3.
**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
struct ListNode* deleteDuplicates(struct ListNode* head) {
}
I have the written the solution for it, but looking for more ideas and suggestions. This solution has passed all the 166 test cases from leetcode.
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
struct ListNode* deleteDuplicates(struct ListNode* head) {
struct ListNode * current = head, *nextNode, *temp;
//No elements
if(head == NULL)
{
return NULL;
}
//Single element linked list
if(head->next == NULL)
{
return head;
}
//if the numbers are repeating from the beginning;;
//then we need to move head;
while(head !=NULL && head->next !=NULL && head->val == head->next->val){
if( head->val == head->next->val)
{
nextNode = head->next;
while(nextNode !=NULL && head->val == nextNode->val){
temp = nextNode;
nextNode = nextNode->next;
free(temp);
}
temp = head;
head = nextNode;
current = head;
free(temp);
}
}
//Again a check to see if the list is empty
if(head == NULL)
{
return NULL;
}
while(current->next != NULL){
nextNode = current->next;
if(nextNode->next !=NULL && nextNode->val == nextNode->next->val){
while(nextNode->next !=NULL && nextNode->val == nextNode->next->val){
temp = nextNode->next;
nextNode->next = temp->next;
}
current->next = nextNode->next;
}else {
current = nextNode;
}
}
return head;
}