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.
- Another part of the base case is if head==NULL, but index!=0. Stop. Overrun. Return head.
- Recursion step: Here head!=null and index!=0 is true.
head->next = the starting of the remaining list = f(head->next, data, index).
- It is important to remember that remaking this already connection, i.e a system’s property helps us write the recursion without making a helper function.
- Hence we don’t have to use a helper function.
New(?intuition) skill learnt !!