Explanation Of This Recursive Method: | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

Explanation Of This Recursive Method:

Can I have an explaination of the process of the recursion here and what is being returned for what pupose? (Its a linkedlist insertion code): private Node addParam(Node node, int key){ if (node == null){ node = new Node(key); return node; }else{ node.next = addParam(node.next, key); return node; } } public void add(int key){ this.root = addParam(this.root, key); }

19th Jun 2021, 12:45 PM
Yahel
Yahel - avatar
1 Answer
0
So this looks like a singly linked list. Each node holds a value (key) and a link to the following node (next). When the list is empty, it only has the root node with next pointing to null. This code walks through all the nodes, starting from root, and it adds a new node at the end, with the key provided. The add() method is called from outside, and it just invokes addParam and reassigns the result to the root node. Lets see what happens when the list is empty and we use add(1) 1. addParam(this.root, 1) invoked 2. The if condition is false because the root node is not null, so addParam is called a second time but now with addParam(null, 1) 3. We reach the base case of the recursion (end of list). New node created and returned. 4. The new node is reassigned to this.root.next (back in step 2) then root node is returned. 5. root node is reassigned to itself (back in step 1) If the list already has elements, the same thing happens, reassigning each node to itself when unrolling the recursion stack.
19th Jun 2021, 2:13 PM
Tibor Santa
Tibor Santa - avatar