简体   繁体   中英

How exactly does a recursive method return a final value and assign its result(s)?

LinkedListNode addLists(LinkedListNode l1, LinkedListNode l2, int carry) {

    if(l1 == null && l2 == null && carry == 0) {
      return null;
    }

    LinkedListNode result = new LinkedListNode(carry,null,null);
    int value = carry;
    if(l1 != null) 
      value += l1.data;

    if(l2 != null)
      value += l2.data;

    result.data = value % 10;

    //Recursive call
    if(l1 != null || l2 != null || value >= 10) {
      LinkedListNode more = addLists(l1 == null? null : l1.next,
                                     l2 == null? null : l2.next,
                                     value >= 10? 1 : 0);
      result.setNext(more);
    }
    return result;
}

My doubts with the recursive call of addLists(arg1,arg2,arg3) are:

  1. What exactly is stored at more after each recursive call? In other words, will more stack up the result of each recursive call?
  2. Will the statement (after the recursive call), result.setNext(more) , be executed in every recursive call?
  3. How will the final return value work?

I understand the concept of recursion and have gone through various other answers. However, the scenario of return statement along with the recursive call being assigned to more seem different, and have made it confusing. Would really appreciate a simple explanation of this scenario. Thanks.

It might feel like magic but it really isn't. In your code you might call methods sequentially like this:

System.out.println("first line");
System.out.println("second line");

but you never question why it prints "second line". It resumes execution when the printing of "first line" is finished.

With recursion it's the same. At one point it hits a base case. In your code its when both the nodes are null and carry is less than 10. Then it finishes by returning and if it was a recursive call the value will be added and this instance of the method will return etc. all the way up to the initial callee which then will continue executing the next line in the same manner as the two System.out.println lines in my example.

Everytime you call a method the variables are different than the previous. So even if there are 10 levels of calls they all have their own l1 , l2 , carry , and even more and they will all continue with the next line when the current method returns just as any other methiod. Recursive methods are not that special!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM