Delete without head pointer

Delete without head pointer

You are given a reference to the node which is to be deleted from the linked list of nodes. The task is to delete the node.

 
Note: No head reference is given to you.

Ex: 1->3->2->4->6  you are given a pointer to node 2 you have to delete that node and you dont have the head node pointer.

    Output will be  1->3->4->6

Explanation:

  • let the list be 1->3-> 2 ->4->6   we have a pointer at node 2 
  Node class looks like 
  class Node{
        int data;
        Node next;
            Node(int data)
            {
                this.data=data;
                this.next=NULL;
            }
    }

  •  So what we can do is copy the data of the next node to the current node and make the pointer of the current node pointing to the  next of the next node.
  • Means say list is 1->3-> 2 ->4->6 , and we have pointer to node 2, now  if we copy the data of the next node to the current node .
  • The list will be 1->3-> 4 ->4->6 we still have pointer to that node just we replace its data with the neighbours  data.
  • Now we make the next pointer to point to the node with data 6
  • Thus the list will be 1->3->4->6 .
Code:
 
void deleteNode(Node node)
    {
         if(node.next!=null)
         {
             node.data=node.next.data;
             node.next=node.next.next;

        }
              
    } 

lets evaluate the code:
list: 1->3->2->4->6
  •  we have pointer to node 2, we check if it is last node or not. Now we copy the data to the our current node , and make its next to point next of nodes next.

  • node 2: data becomes 4 , next pointer will be node.next.next i.e next of 2 and its next which is 6 so the duplicate value that will be formed by coping data from the neighbours will not be considered as list uses pointer or references .

                                            

Post a Comment

0 Comments