7. Insert Node recursive #

Created Friday 17 January 2020

Node* insertNodeRec(Node head, int i, int data) { if(head==NULL && i!=0) return head; if(i==0) { Node newnode = new Node(data); newnode->next = head; return newnode; // insertion at the beginning }

head->next = insertNodeRec(head->next, i-1, data); // traverses to the next element, makes a connection to the list which is present return head; }

How does it work? A) We insert at the beginning only. This is the base case case and easy to check. Return the newnode’s address.

head->next = the starting of the remaining list = f(head->next, data, index).

New(?intuition) skill learnt !!