Sunday, 17 July 2016

Remove Linked List Elements

Remove all elements from a linked list of integers that have value val.
Example
Given: 1 --> 2 --> 6 --> 3 --> 4 --> 5 --> 6, val = 6
Return: 1 --> 2 --> 3 --> 4 --> 5

 /**  
  * Definition for singly-linked list.  
  * struct ListNode {  
  *   int val;  
  *   struct ListNode *next;  
  * };  
  */  
 struct ListNode* removeElements(struct ListNode* head, int val) {  
   struct ListNode *n1, *n2;  
   if(head == NULL)  
     return NULL;  
   while(head->val == val){  
     if(head->next != NULL)  
       head = head->next;  
     else{  
       head = NULL;  
       return head;  
     }  
   }  
   n1 = head;  
   n2 = NULL;  
   while(n1){  
     if(n1->val == val){  
       if(n1->next){  
         n2->next = n1->next;  
       }else{  
         n2->next = NULL;  
       }  
     }  
     else{  
       n2 = n1;  
     }  
     n1 = n1->next;  
   }  
   return head;  
 }  
Share:

0 comments:

Post a Comment

Contact Me

Name

Email *

Message *

Popular Posts

Blog Archive