Deletion in mid in linked lists

sir, i tried this question lnk:https://leetcode.com/problems/remove-linked-list-elements/
but it is giving undefined memory i think some problem related with function
/**

  • Definition for singly-linked list.

  • struct ListNode {

  • int val;
    
  • ListNode *next;
    
  • ListNode() : val(0), next(nullptr) {}
    
  • ListNode(int x) : val(x), next(nullptr) {}
    
  • ListNode(int x, ListNode *next) : val(x), next(next) {}
    
  • };
    */
    class Solution
    {
    public:
    void remove(ListNode *temp,ListNode *prev)
    {
    ListNode *del = temp;
    prev -> next = temp -> next;
    temp = temp -> next;
    delete(del);
    cout<val<<" "<val<<endl;
    }

    ListNode* removeElements(ListNode* head, int data)
    {
    ListNode *temp = head;
    ListNode *prev = NULL;
    while(temp->next!=NULL)
    {
    if(temp->val == data)
    {
    remove(temp,prev);
    cout<val<<" "<val<<endl;

         }
         else
         {
             prev = temp;
             temp = temp->next;
         }
     }
     
     return head;
    

    }
    };

sir use this link to open the code instead link:https://ide.codingblocks.com/s/291784

hello @khushi91200


a)pass them as refernce
b) prev can be NULL so handle that case separately.

c)
image
here it should be temp!=NULL;
d) ur head can also be deleted to add such cases as well

how to pass it as reference sir?

sir i know the rest case i will do it i am confused only how to do it by refernce coz pointers are passed by reference

like this->
void func( node * &p){

}

thanks sir it worked but sir pointers are passed by reference

so why we are explicitly making it as reference

pointers are also a variable .they just contain address.
so whathever behaviour we expect from any variable of any other type.
same holds true for pointers.

means pointers are passed by value not reference?

yeah…
they r special because they contain addresses .

ok sir thankyou!!!