Java – query the usage of this variable in recursion
After calling the method,
node.nth(5)
In the following code,
public class List_Node { int item; List_Node next; public List_Node() { this.item = 0; this.next = null; } public List_Node(int item,List_Node next) { this.item = item; this.next = next; } public List_Node(int item) { this(item,null); } public void insertAfter(int item) { this.next = new List_Node(item,this.next); } public List_Node nth(int position) { if (position == 1) { return this; } else if((position < 1) || (this.next == null)) { /* error checking */ return null; } else { return this.next.nth(position - 1); } } public static void main(String[] args){ List_Node node = new List_Node(0); List_Node temp = node; for (int item = 1; item < 5; item++) { temp.insertAfter(item); temp = temp.next; } System.out.println(node.nth(5).item); } }
The following is the stack frame of the nth () method I can imagine after four recursive calls
My question:
According to the above figure, assuming that the value in the activation record S5 is pos is 1, I want to know what happens when Java returns this point during execution? In S4, does Java assign a value to this value? Because there is no assignment statement in the else {} block of the nth () method
Note: please ignore the Java coding style, just like new learners
Solution
Every time you call this next. When nth (), the nth () method is called on completely different objects Your will reference the new object (next on the previous stack) It is not purely recursive It's like calling different methods on different objects
So when position = 1, this will refer to S5
Update let's talk about your list_ Nodes are linked as follows: 10 → 20 →; 30-> 40-→50
Whenever you call node. From main nth(5)
Stack 1: position 5,this points to 10 (you are calling this.next.nth(4); means 20.nth()) Stack 2: position 4,this points to 20 (calling this.next.nth(3); = 30.nth()) Stack 3: position 3,this points to 30 (calling this.next.nth(2) = 40.nth()) Stack 4: position 2,this points to 40 (calling this.next.nth(1) = 50.nth()) Stack 5: position 1,this points to 50 (returning this; this here is 50) returns 50 returns 50 (not going back into if,so return value remains same) returns 50 returns 50 returns 50
While chatting, this is also described in the picture Add here to benefit future readers
Another update
No assignment variable in else as such
You can write like this
List_Node temp = this.next.nth(position-1); return temp;
Generally speaking, we need to separate the list and node classes. Your list should have a header, and your node will have item and next pointers Just like LinkedList in Java Then the nth () method will be in the list class, and it just iterates through it until it reaches the nth element