pranay_teja
11/20/2018 - 5:56 AM

RemoveLLElementsWithGivenVal

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode* removeElements(ListNode* head, int val) {
        
        // Method B: Recursive approach
        if(head==NULL){
            return head; // base case
        }
        // remove elements to the right of LL
        head->next=removeElements(head->next,val);
        if( head->val==val){
            head=head->next; // if head is to be deleted new head is head->next
        }
        return head;
        
        
        
        
//         // Method A: declare a dummy infront of head
//         ListNode* dummy=new ListNode(0);
//         dummy->next=head;
        
//         // start with prev at dummy and curr at head
//         ListNode* prev=dummy;
//         ListNode* curr=head;
        
//         // loop until curr reaches end of LL
//         while(curr!=NULL){
//             if(curr->val==val){
//                 ListNode* temp=curr;
//                 curr=curr->next;
//                 prev->next=curr;
//                 delete temp;
//                 continue;
//             }
//             curr=curr->next;
//             prev=prev->next;
//         }
//         // dummy->next always keeps track of new head
//         head=dummy->next;
//         delete dummy;
//         return head;
    }
};