Remove Duplicates from Sorted List -- LeetCode Solution in C 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-&gt;next == NULL)
 {
     return head;
 }

     //if the numbers are repeating from the beginning;;
     //then we need to move head;
     while(head !=NULL &amp;&amp; head-&gt;next !=NULL &amp;&amp; head-&gt;val == head-&gt;next-&gt;val){
     if( head-&gt;val == head-&gt;next-&gt;val)
     {
         nextNode = head-&gt;next;
         while(nextNode !=NULL  &amp;&amp; head-&gt;val == nextNode-&gt;val){
            temp = nextNode;
        nextNode = nextNode-&gt;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-&gt;next != NULL){

     nextNode = current-&gt;next;



        if(nextNode-&gt;next !=NULL  &amp;&amp; nextNode-&gt;val == nextNode-&gt;next-&gt;val){         

         while(nextNode-&gt;next !=NULL  &amp;&amp; nextNode-&gt;val == nextNode-&gt;next-&gt;val){
            temp = nextNode-&gt;next;
        nextNode-&gt;next = temp-&gt;next;
         }
        current-&gt;next = nextNode-&gt;next;

        }else {
            current = nextNode;   
        }

 }

return head;


}
You can use a simple recursive method like this: basically, we only need to care about the previous node and current node when deleting a node.

ListNode* deleteDuplicates(struct ListNode* head) {
     deleteDuplicates(NULL, head);
     return head;
}

void deleteDuplicates(struct ListNode* pre, struct ListNode* cur) {
   if(cur == NULL)
      return;
   if(pre == NULL){
      deleteDuplicates(cur, cur-&gt;next);
   }else if(pre-&gt;val == cur-&gt;val){//Delete duplicate node
      pre-&gt;next = cur-&gt;next;
      deleteDuplicates(pre, pre -&gt;next);
   }else{//The current node doesn't need to be deleted, move forward
      deleteDuplicates(cur, cur-&gt;next);
   }
}