Recursion In Merging Linked Lists












0















I am beginning to understand recursion,



I have attached the recursion code to merge two sorted linked lists,



My problem is, I understand that 'temp' returns the value of temp->(first (or) second) once the first or second becomes null, but I am unable to understand the fact that,



Say for instance if I have 5 -> 10 -> 15 -> 20.



The final function returns 15 ->20 which is then combined as root.next-> temp, but after that step when I return temp, why does the root value gets returned.
i.e 10 -> 15 -> 20, when I expect only temp to be returned.



Please find the code,



 /**
*
*/
*
*
*/
public class MergeLinkedLists {

static class Node {

int data;
Node next;

public Node(int value) {
this.data = value;
}

}

Node root;

/**
* @param args
*/

public static void main(String args) {
// TODO Auto-generated method stub
MergeLinkedLists s1 = new MergeLinkedLists();
s1.root = new Node(0);
Node n1 = new Node(10);
//n1.next = new Node(20);
//n1.next.next = new Node(30);

Node n2 = new Node(5);
n2.next = new Node(15);
//n2.next.next = new Node(50);

Node result = sortedLists(n1, n2, s1.root);

while (result != null) {
System.out.print(result.data + "--->");
result = result.next;
}
}

/**
* @param n1
* @param n2
* @param root2
*/
private static Node sortedLists(Node n1, Node n2, Node root) {
// TODO Auto-generated method stub

Node temp = root;

Node first = n1; // 10 20 30
Node second = n2; // 5 15 50

if (first == null) {
temp.next = second;
return temp;
} else if (second == null) {
temp.next = first;
return temp;
}

else if (first.data < second.data) {
temp = new Node(first.data);
first = first.next;
} else {
temp = new Node(second.data);
second = second.next;
}

sortedLists(first, second, temp);
root.next = temp;
System.out.println("The Temp Data is ::::"+temp.data);
return temp;

}

}









share|improve this question

























  • Welcome to SO! This function is written in a pretty confusing manner, but works just fine as far as I can tell. Can you clarify what your problem is? Your return values here don't matter except for the first function call, which is returning the correct result (the dummy root's next value, i.e. root.next) to the main scope.

    – ggorlen
    Nov 24 '18 at 7:17
















0















I am beginning to understand recursion,



I have attached the recursion code to merge two sorted linked lists,



My problem is, I understand that 'temp' returns the value of temp->(first (or) second) once the first or second becomes null, but I am unable to understand the fact that,



Say for instance if I have 5 -> 10 -> 15 -> 20.



The final function returns 15 ->20 which is then combined as root.next-> temp, but after that step when I return temp, why does the root value gets returned.
i.e 10 -> 15 -> 20, when I expect only temp to be returned.



Please find the code,



 /**
*
*/
*
*
*/
public class MergeLinkedLists {

static class Node {

int data;
Node next;

public Node(int value) {
this.data = value;
}

}

Node root;

/**
* @param args
*/

public static void main(String args) {
// TODO Auto-generated method stub
MergeLinkedLists s1 = new MergeLinkedLists();
s1.root = new Node(0);
Node n1 = new Node(10);
//n1.next = new Node(20);
//n1.next.next = new Node(30);

Node n2 = new Node(5);
n2.next = new Node(15);
//n2.next.next = new Node(50);

Node result = sortedLists(n1, n2, s1.root);

while (result != null) {
System.out.print(result.data + "--->");
result = result.next;
}
}

/**
* @param n1
* @param n2
* @param root2
*/
private static Node sortedLists(Node n1, Node n2, Node root) {
// TODO Auto-generated method stub

Node temp = root;

Node first = n1; // 10 20 30
Node second = n2; // 5 15 50

if (first == null) {
temp.next = second;
return temp;
} else if (second == null) {
temp.next = first;
return temp;
}

else if (first.data < second.data) {
temp = new Node(first.data);
first = first.next;
} else {
temp = new Node(second.data);
second = second.next;
}

sortedLists(first, second, temp);
root.next = temp;
System.out.println("The Temp Data is ::::"+temp.data);
return temp;

}

}









share|improve this question

























  • Welcome to SO! This function is written in a pretty confusing manner, but works just fine as far as I can tell. Can you clarify what your problem is? Your return values here don't matter except for the first function call, which is returning the correct result (the dummy root's next value, i.e. root.next) to the main scope.

    – ggorlen
    Nov 24 '18 at 7:17














0












0








0








I am beginning to understand recursion,



I have attached the recursion code to merge two sorted linked lists,



My problem is, I understand that 'temp' returns the value of temp->(first (or) second) once the first or second becomes null, but I am unable to understand the fact that,



Say for instance if I have 5 -> 10 -> 15 -> 20.



The final function returns 15 ->20 which is then combined as root.next-> temp, but after that step when I return temp, why does the root value gets returned.
i.e 10 -> 15 -> 20, when I expect only temp to be returned.



Please find the code,



 /**
*
*/
*
*
*/
public class MergeLinkedLists {

static class Node {

int data;
Node next;

public Node(int value) {
this.data = value;
}

}

Node root;

/**
* @param args
*/

public static void main(String args) {
// TODO Auto-generated method stub
MergeLinkedLists s1 = new MergeLinkedLists();
s1.root = new Node(0);
Node n1 = new Node(10);
//n1.next = new Node(20);
//n1.next.next = new Node(30);

Node n2 = new Node(5);
n2.next = new Node(15);
//n2.next.next = new Node(50);

Node result = sortedLists(n1, n2, s1.root);

while (result != null) {
System.out.print(result.data + "--->");
result = result.next;
}
}

/**
* @param n1
* @param n2
* @param root2
*/
private static Node sortedLists(Node n1, Node n2, Node root) {
// TODO Auto-generated method stub

Node temp = root;

Node first = n1; // 10 20 30
Node second = n2; // 5 15 50

if (first == null) {
temp.next = second;
return temp;
} else if (second == null) {
temp.next = first;
return temp;
}

else if (first.data < second.data) {
temp = new Node(first.data);
first = first.next;
} else {
temp = new Node(second.data);
second = second.next;
}

sortedLists(first, second, temp);
root.next = temp;
System.out.println("The Temp Data is ::::"+temp.data);
return temp;

}

}









share|improve this question
















I am beginning to understand recursion,



I have attached the recursion code to merge two sorted linked lists,



My problem is, I understand that 'temp' returns the value of temp->(first (or) second) once the first or second becomes null, but I am unable to understand the fact that,



Say for instance if I have 5 -> 10 -> 15 -> 20.



The final function returns 15 ->20 which is then combined as root.next-> temp, but after that step when I return temp, why does the root value gets returned.
i.e 10 -> 15 -> 20, when I expect only temp to be returned.



Please find the code,



 /**
*
*/
*
*
*/
public class MergeLinkedLists {

static class Node {

int data;
Node next;

public Node(int value) {
this.data = value;
}

}

Node root;

/**
* @param args
*/

public static void main(String args) {
// TODO Auto-generated method stub
MergeLinkedLists s1 = new MergeLinkedLists();
s1.root = new Node(0);
Node n1 = new Node(10);
//n1.next = new Node(20);
//n1.next.next = new Node(30);

Node n2 = new Node(5);
n2.next = new Node(15);
//n2.next.next = new Node(50);

Node result = sortedLists(n1, n2, s1.root);

while (result != null) {
System.out.print(result.data + "--->");
result = result.next;
}
}

/**
* @param n1
* @param n2
* @param root2
*/
private static Node sortedLists(Node n1, Node n2, Node root) {
// TODO Auto-generated method stub

Node temp = root;

Node first = n1; // 10 20 30
Node second = n2; // 5 15 50

if (first == null) {
temp.next = second;
return temp;
} else if (second == null) {
temp.next = first;
return temp;
}

else if (first.data < second.data) {
temp = new Node(first.data);
first = first.next;
} else {
temp = new Node(second.data);
second = second.next;
}

sortedLists(first, second, temp);
root.next = temp;
System.out.println("The Temp Data is ::::"+temp.data);
return temp;

}

}






java recursion data-structures linked-list






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 24 '18 at 2:29









W.Ambrozic

901212




901212










asked Nov 24 '18 at 1:36









stevensstevens

32




32













  • Welcome to SO! This function is written in a pretty confusing manner, but works just fine as far as I can tell. Can you clarify what your problem is? Your return values here don't matter except for the first function call, which is returning the correct result (the dummy root's next value, i.e. root.next) to the main scope.

    – ggorlen
    Nov 24 '18 at 7:17



















  • Welcome to SO! This function is written in a pretty confusing manner, but works just fine as far as I can tell. Can you clarify what your problem is? Your return values here don't matter except for the first function call, which is returning the correct result (the dummy root's next value, i.e. root.next) to the main scope.

    – ggorlen
    Nov 24 '18 at 7:17

















Welcome to SO! This function is written in a pretty confusing manner, but works just fine as far as I can tell. Can you clarify what your problem is? Your return values here don't matter except for the first function call, which is returning the correct result (the dummy root's next value, i.e. root.next) to the main scope.

– ggorlen
Nov 24 '18 at 7:17





Welcome to SO! This function is written in a pretty confusing manner, but works just fine as far as I can tell. Can you clarify what your problem is? Your return values here don't matter except for the first function call, which is returning the correct result (the dummy root's next value, i.e. root.next) to the main scope.

– ggorlen
Nov 24 '18 at 7:17












1 Answer
1






active

oldest

votes


















0














Because temp is in this case the root value. Don't worry, this is the one thing you need to understand in order to understand recursion itself.



A great feature to understand the functionality of your code is to use the debugger. Set a breakpoint to the function call and you can step through the program, while you can observe how the variables change.



This aside, let's have a look at your code.



Important to note is that whenever you call your sortedLists(first, second, temp); the pointer will get into it until the function terminates (so when it returns temp). You will call this function multiple times as the program continues, so it will get deeper into its own function.
It then carries the information step-by-step on level up until the first call of sortedLists(first, second, temp); terminates and this is in your main method Node result = sortedLists(n1, n2, s1.root);



I will try to get along with your example:




  1. Node result = sortedLists(n1, n2, s1.root);called in the main()method. So the root is 0 and you have your nodes 10 and 5,15.


  2. In the first call of sortedLists() temp becomes 5 and second now carries a 15, because first.data > second.data.



  3. NOW You call the method sortedLists()again but with new values: the root is now 5, first remains 10 and second is 15. We step inside the function and start with the new values:




    1. because of first.data < second.data, temp becomes 10, first is now null.

    2. and again: we reached another call on sortedLists(). We pass the values: first = null second = 15 root = 10 to the function and go one step deeper.


      1. as first is now zero, temp.next will be second(15)

      2. temp looks like this now: 10->15 and we return. (this is the first time, sortedLists() terminates!)



    3. We are now back here and can move on with root.next = temp; Remember what temp was in this context? temp was 10 but it has been updated by the function above. The new temp is 10->15, so our root looks like: 5->10->15.

    4. Then you print the head of temp, which is 10. This function also terminates.



  4. now we are back in our first call and see what happens: in 3.3 we updated the root of it. The root of 3.3 was the temp of 3 because we called sortedLists(first, second, temp) (temp acts as the root because the last argument of this function is Node root).


  5. To sum up: Our root is still 0 and our temp is 5->10->15


  6. root.next is after this assignment 0->5->10->15. Now the root you declared in your class above the main method has a value.


  7. we return the temp which is 5->10->15 and we are done.



We now can proceed in the main method, printing the results.



To get rid of the ---> when there is no result.next, you can handle the null value like this:



 while (result != null) {
if (result.next != null)
System.out.print(result.data + "--->");
else System.out.println(result.data);
result = result.next;
}


I hope this helps a bit to get into recursion.






share|improve this answer


























  • Hi e.Fro, Thanks a lot for your suggestion, I have a small doubt in the step number 4 where you say that, root of 3.3 is temp of 3 ...I get that...but when 3.3's function call is terminated, how come the root value is returned ....where i am only returning temp. ( 10-> 15) .... so does all the values get returned to previous calling function.... Thanks in advance.

    – stevens
    Nov 24 '18 at 14:34











  • I guess the entire concept, is based on pass by value, as the called function's root value is updated it is reflected back in the calling function's temp value. Please correct me if I am wrong !

    – stevens
    Nov 24 '18 at 15:57













  • One thing to keep in mind about objects in Java is that they are unique unless you recreate them (new object()). So your function passes the temp object and the called function assigns the same object to be the root. But the object itself remains the same. So if you change it, you don’t just change its value, you Operation will have impact to the whole object. This is a massive advantage since you can save much of space. So there is no need to return, that’s why you don’t process the returns in the recursion. You simply manipulate the object itself

    – e.Fro
    Nov 24 '18 at 16:04











  • This approach is called in-place, and is also used by quick sort. In the context of liked lists it is very useful to use because you don’t want to keep on creating new elements for manipulation. I hope I can help you a little bit with that. en.m.wikipedia.org/wiki/In-place_algorithm

    – e.Fro
    Nov 24 '18 at 16:07











  • I recommend using the debugger on your method, to see when the temp objects on the upper levels change. I think this will help a lot.

    – e.Fro
    Nov 24 '18 at 16:12











Your Answer






StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");

StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "1"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);

StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});

function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});


}
});














draft saved

draft discarded


















StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53454456%2frecursion-in-merging-linked-lists%23new-answer', 'question_page');
}
);

Post as a guest















Required, but never shown

























1 Answer
1






active

oldest

votes








1 Answer
1






active

oldest

votes









active

oldest

votes






active

oldest

votes









0














Because temp is in this case the root value. Don't worry, this is the one thing you need to understand in order to understand recursion itself.



A great feature to understand the functionality of your code is to use the debugger. Set a breakpoint to the function call and you can step through the program, while you can observe how the variables change.



This aside, let's have a look at your code.



Important to note is that whenever you call your sortedLists(first, second, temp); the pointer will get into it until the function terminates (so when it returns temp). You will call this function multiple times as the program continues, so it will get deeper into its own function.
It then carries the information step-by-step on level up until the first call of sortedLists(first, second, temp); terminates and this is in your main method Node result = sortedLists(n1, n2, s1.root);



I will try to get along with your example:




  1. Node result = sortedLists(n1, n2, s1.root);called in the main()method. So the root is 0 and you have your nodes 10 and 5,15.


  2. In the first call of sortedLists() temp becomes 5 and second now carries a 15, because first.data > second.data.



  3. NOW You call the method sortedLists()again but with new values: the root is now 5, first remains 10 and second is 15. We step inside the function and start with the new values:




    1. because of first.data < second.data, temp becomes 10, first is now null.

    2. and again: we reached another call on sortedLists(). We pass the values: first = null second = 15 root = 10 to the function and go one step deeper.


      1. as first is now zero, temp.next will be second(15)

      2. temp looks like this now: 10->15 and we return. (this is the first time, sortedLists() terminates!)



    3. We are now back here and can move on with root.next = temp; Remember what temp was in this context? temp was 10 but it has been updated by the function above. The new temp is 10->15, so our root looks like: 5->10->15.

    4. Then you print the head of temp, which is 10. This function also terminates.



  4. now we are back in our first call and see what happens: in 3.3 we updated the root of it. The root of 3.3 was the temp of 3 because we called sortedLists(first, second, temp) (temp acts as the root because the last argument of this function is Node root).


  5. To sum up: Our root is still 0 and our temp is 5->10->15


  6. root.next is after this assignment 0->5->10->15. Now the root you declared in your class above the main method has a value.


  7. we return the temp which is 5->10->15 and we are done.



We now can proceed in the main method, printing the results.



To get rid of the ---> when there is no result.next, you can handle the null value like this:



 while (result != null) {
if (result.next != null)
System.out.print(result.data + "--->");
else System.out.println(result.data);
result = result.next;
}


I hope this helps a bit to get into recursion.






share|improve this answer


























  • Hi e.Fro, Thanks a lot for your suggestion, I have a small doubt in the step number 4 where you say that, root of 3.3 is temp of 3 ...I get that...but when 3.3's function call is terminated, how come the root value is returned ....where i am only returning temp. ( 10-> 15) .... so does all the values get returned to previous calling function.... Thanks in advance.

    – stevens
    Nov 24 '18 at 14:34











  • I guess the entire concept, is based on pass by value, as the called function's root value is updated it is reflected back in the calling function's temp value. Please correct me if I am wrong !

    – stevens
    Nov 24 '18 at 15:57













  • One thing to keep in mind about objects in Java is that they are unique unless you recreate them (new object()). So your function passes the temp object and the called function assigns the same object to be the root. But the object itself remains the same. So if you change it, you don’t just change its value, you Operation will have impact to the whole object. This is a massive advantage since you can save much of space. So there is no need to return, that’s why you don’t process the returns in the recursion. You simply manipulate the object itself

    – e.Fro
    Nov 24 '18 at 16:04











  • This approach is called in-place, and is also used by quick sort. In the context of liked lists it is very useful to use because you don’t want to keep on creating new elements for manipulation. I hope I can help you a little bit with that. en.m.wikipedia.org/wiki/In-place_algorithm

    – e.Fro
    Nov 24 '18 at 16:07











  • I recommend using the debugger on your method, to see when the temp objects on the upper levels change. I think this will help a lot.

    – e.Fro
    Nov 24 '18 at 16:12
















0














Because temp is in this case the root value. Don't worry, this is the one thing you need to understand in order to understand recursion itself.



A great feature to understand the functionality of your code is to use the debugger. Set a breakpoint to the function call and you can step through the program, while you can observe how the variables change.



This aside, let's have a look at your code.



Important to note is that whenever you call your sortedLists(first, second, temp); the pointer will get into it until the function terminates (so when it returns temp). You will call this function multiple times as the program continues, so it will get deeper into its own function.
It then carries the information step-by-step on level up until the first call of sortedLists(first, second, temp); terminates and this is in your main method Node result = sortedLists(n1, n2, s1.root);



I will try to get along with your example:




  1. Node result = sortedLists(n1, n2, s1.root);called in the main()method. So the root is 0 and you have your nodes 10 and 5,15.


  2. In the first call of sortedLists() temp becomes 5 and second now carries a 15, because first.data > second.data.



  3. NOW You call the method sortedLists()again but with new values: the root is now 5, first remains 10 and second is 15. We step inside the function and start with the new values:




    1. because of first.data < second.data, temp becomes 10, first is now null.

    2. and again: we reached another call on sortedLists(). We pass the values: first = null second = 15 root = 10 to the function and go one step deeper.


      1. as first is now zero, temp.next will be second(15)

      2. temp looks like this now: 10->15 and we return. (this is the first time, sortedLists() terminates!)



    3. We are now back here and can move on with root.next = temp; Remember what temp was in this context? temp was 10 but it has been updated by the function above. The new temp is 10->15, so our root looks like: 5->10->15.

    4. Then you print the head of temp, which is 10. This function also terminates.



  4. now we are back in our first call and see what happens: in 3.3 we updated the root of it. The root of 3.3 was the temp of 3 because we called sortedLists(first, second, temp) (temp acts as the root because the last argument of this function is Node root).


  5. To sum up: Our root is still 0 and our temp is 5->10->15


  6. root.next is after this assignment 0->5->10->15. Now the root you declared in your class above the main method has a value.


  7. we return the temp which is 5->10->15 and we are done.



We now can proceed in the main method, printing the results.



To get rid of the ---> when there is no result.next, you can handle the null value like this:



 while (result != null) {
if (result.next != null)
System.out.print(result.data + "--->");
else System.out.println(result.data);
result = result.next;
}


I hope this helps a bit to get into recursion.






share|improve this answer


























  • Hi e.Fro, Thanks a lot for your suggestion, I have a small doubt in the step number 4 where you say that, root of 3.3 is temp of 3 ...I get that...but when 3.3's function call is terminated, how come the root value is returned ....where i am only returning temp. ( 10-> 15) .... so does all the values get returned to previous calling function.... Thanks in advance.

    – stevens
    Nov 24 '18 at 14:34











  • I guess the entire concept, is based on pass by value, as the called function's root value is updated it is reflected back in the calling function's temp value. Please correct me if I am wrong !

    – stevens
    Nov 24 '18 at 15:57













  • One thing to keep in mind about objects in Java is that they are unique unless you recreate them (new object()). So your function passes the temp object and the called function assigns the same object to be the root. But the object itself remains the same. So if you change it, you don’t just change its value, you Operation will have impact to the whole object. This is a massive advantage since you can save much of space. So there is no need to return, that’s why you don’t process the returns in the recursion. You simply manipulate the object itself

    – e.Fro
    Nov 24 '18 at 16:04











  • This approach is called in-place, and is also used by quick sort. In the context of liked lists it is very useful to use because you don’t want to keep on creating new elements for manipulation. I hope I can help you a little bit with that. en.m.wikipedia.org/wiki/In-place_algorithm

    – e.Fro
    Nov 24 '18 at 16:07











  • I recommend using the debugger on your method, to see when the temp objects on the upper levels change. I think this will help a lot.

    – e.Fro
    Nov 24 '18 at 16:12














0












0








0







Because temp is in this case the root value. Don't worry, this is the one thing you need to understand in order to understand recursion itself.



A great feature to understand the functionality of your code is to use the debugger. Set a breakpoint to the function call and you can step through the program, while you can observe how the variables change.



This aside, let's have a look at your code.



Important to note is that whenever you call your sortedLists(first, second, temp); the pointer will get into it until the function terminates (so when it returns temp). You will call this function multiple times as the program continues, so it will get deeper into its own function.
It then carries the information step-by-step on level up until the first call of sortedLists(first, second, temp); terminates and this is in your main method Node result = sortedLists(n1, n2, s1.root);



I will try to get along with your example:




  1. Node result = sortedLists(n1, n2, s1.root);called in the main()method. So the root is 0 and you have your nodes 10 and 5,15.


  2. In the first call of sortedLists() temp becomes 5 and second now carries a 15, because first.data > second.data.



  3. NOW You call the method sortedLists()again but with new values: the root is now 5, first remains 10 and second is 15. We step inside the function and start with the new values:




    1. because of first.data < second.data, temp becomes 10, first is now null.

    2. and again: we reached another call on sortedLists(). We pass the values: first = null second = 15 root = 10 to the function and go one step deeper.


      1. as first is now zero, temp.next will be second(15)

      2. temp looks like this now: 10->15 and we return. (this is the first time, sortedLists() terminates!)



    3. We are now back here and can move on with root.next = temp; Remember what temp was in this context? temp was 10 but it has been updated by the function above. The new temp is 10->15, so our root looks like: 5->10->15.

    4. Then you print the head of temp, which is 10. This function also terminates.



  4. now we are back in our first call and see what happens: in 3.3 we updated the root of it. The root of 3.3 was the temp of 3 because we called sortedLists(first, second, temp) (temp acts as the root because the last argument of this function is Node root).


  5. To sum up: Our root is still 0 and our temp is 5->10->15


  6. root.next is after this assignment 0->5->10->15. Now the root you declared in your class above the main method has a value.


  7. we return the temp which is 5->10->15 and we are done.



We now can proceed in the main method, printing the results.



To get rid of the ---> when there is no result.next, you can handle the null value like this:



 while (result != null) {
if (result.next != null)
System.out.print(result.data + "--->");
else System.out.println(result.data);
result = result.next;
}


I hope this helps a bit to get into recursion.






share|improve this answer















Because temp is in this case the root value. Don't worry, this is the one thing you need to understand in order to understand recursion itself.



A great feature to understand the functionality of your code is to use the debugger. Set a breakpoint to the function call and you can step through the program, while you can observe how the variables change.



This aside, let's have a look at your code.



Important to note is that whenever you call your sortedLists(first, second, temp); the pointer will get into it until the function terminates (so when it returns temp). You will call this function multiple times as the program continues, so it will get deeper into its own function.
It then carries the information step-by-step on level up until the first call of sortedLists(first, second, temp); terminates and this is in your main method Node result = sortedLists(n1, n2, s1.root);



I will try to get along with your example:




  1. Node result = sortedLists(n1, n2, s1.root);called in the main()method. So the root is 0 and you have your nodes 10 and 5,15.


  2. In the first call of sortedLists() temp becomes 5 and second now carries a 15, because first.data > second.data.



  3. NOW You call the method sortedLists()again but with new values: the root is now 5, first remains 10 and second is 15. We step inside the function and start with the new values:




    1. because of first.data < second.data, temp becomes 10, first is now null.

    2. and again: we reached another call on sortedLists(). We pass the values: first = null second = 15 root = 10 to the function and go one step deeper.


      1. as first is now zero, temp.next will be second(15)

      2. temp looks like this now: 10->15 and we return. (this is the first time, sortedLists() terminates!)



    3. We are now back here and can move on with root.next = temp; Remember what temp was in this context? temp was 10 but it has been updated by the function above. The new temp is 10->15, so our root looks like: 5->10->15.

    4. Then you print the head of temp, which is 10. This function also terminates.



  4. now we are back in our first call and see what happens: in 3.3 we updated the root of it. The root of 3.3 was the temp of 3 because we called sortedLists(first, second, temp) (temp acts as the root because the last argument of this function is Node root).


  5. To sum up: Our root is still 0 and our temp is 5->10->15


  6. root.next is after this assignment 0->5->10->15. Now the root you declared in your class above the main method has a value.


  7. we return the temp which is 5->10->15 and we are done.



We now can proceed in the main method, printing the results.



To get rid of the ---> when there is no result.next, you can handle the null value like this:



 while (result != null) {
if (result.next != null)
System.out.print(result.data + "--->");
else System.out.println(result.data);
result = result.next;
}


I hope this helps a bit to get into recursion.







share|improve this answer














share|improve this answer



share|improve this answer








edited Nov 24 '18 at 10:33

























answered Nov 24 '18 at 10:27









e.Froe.Fro

186




186













  • Hi e.Fro, Thanks a lot for your suggestion, I have a small doubt in the step number 4 where you say that, root of 3.3 is temp of 3 ...I get that...but when 3.3's function call is terminated, how come the root value is returned ....where i am only returning temp. ( 10-> 15) .... so does all the values get returned to previous calling function.... Thanks in advance.

    – stevens
    Nov 24 '18 at 14:34











  • I guess the entire concept, is based on pass by value, as the called function's root value is updated it is reflected back in the calling function's temp value. Please correct me if I am wrong !

    – stevens
    Nov 24 '18 at 15:57













  • One thing to keep in mind about objects in Java is that they are unique unless you recreate them (new object()). So your function passes the temp object and the called function assigns the same object to be the root. But the object itself remains the same. So if you change it, you don’t just change its value, you Operation will have impact to the whole object. This is a massive advantage since you can save much of space. So there is no need to return, that’s why you don’t process the returns in the recursion. You simply manipulate the object itself

    – e.Fro
    Nov 24 '18 at 16:04











  • This approach is called in-place, and is also used by quick sort. In the context of liked lists it is very useful to use because you don’t want to keep on creating new elements for manipulation. I hope I can help you a little bit with that. en.m.wikipedia.org/wiki/In-place_algorithm

    – e.Fro
    Nov 24 '18 at 16:07











  • I recommend using the debugger on your method, to see when the temp objects on the upper levels change. I think this will help a lot.

    – e.Fro
    Nov 24 '18 at 16:12



















  • Hi e.Fro, Thanks a lot for your suggestion, I have a small doubt in the step number 4 where you say that, root of 3.3 is temp of 3 ...I get that...but when 3.3's function call is terminated, how come the root value is returned ....where i am only returning temp. ( 10-> 15) .... so does all the values get returned to previous calling function.... Thanks in advance.

    – stevens
    Nov 24 '18 at 14:34











  • I guess the entire concept, is based on pass by value, as the called function's root value is updated it is reflected back in the calling function's temp value. Please correct me if I am wrong !

    – stevens
    Nov 24 '18 at 15:57













  • One thing to keep in mind about objects in Java is that they are unique unless you recreate them (new object()). So your function passes the temp object and the called function assigns the same object to be the root. But the object itself remains the same. So if you change it, you don’t just change its value, you Operation will have impact to the whole object. This is a massive advantage since you can save much of space. So there is no need to return, that’s why you don’t process the returns in the recursion. You simply manipulate the object itself

    – e.Fro
    Nov 24 '18 at 16:04











  • This approach is called in-place, and is also used by quick sort. In the context of liked lists it is very useful to use because you don’t want to keep on creating new elements for manipulation. I hope I can help you a little bit with that. en.m.wikipedia.org/wiki/In-place_algorithm

    – e.Fro
    Nov 24 '18 at 16:07











  • I recommend using the debugger on your method, to see when the temp objects on the upper levels change. I think this will help a lot.

    – e.Fro
    Nov 24 '18 at 16:12

















Hi e.Fro, Thanks a lot for your suggestion, I have a small doubt in the step number 4 where you say that, root of 3.3 is temp of 3 ...I get that...but when 3.3's function call is terminated, how come the root value is returned ....where i am only returning temp. ( 10-> 15) .... so does all the values get returned to previous calling function.... Thanks in advance.

– stevens
Nov 24 '18 at 14:34





Hi e.Fro, Thanks a lot for your suggestion, I have a small doubt in the step number 4 where you say that, root of 3.3 is temp of 3 ...I get that...but when 3.3's function call is terminated, how come the root value is returned ....where i am only returning temp. ( 10-> 15) .... so does all the values get returned to previous calling function.... Thanks in advance.

– stevens
Nov 24 '18 at 14:34













I guess the entire concept, is based on pass by value, as the called function's root value is updated it is reflected back in the calling function's temp value. Please correct me if I am wrong !

– stevens
Nov 24 '18 at 15:57







I guess the entire concept, is based on pass by value, as the called function's root value is updated it is reflected back in the calling function's temp value. Please correct me if I am wrong !

– stevens
Nov 24 '18 at 15:57















One thing to keep in mind about objects in Java is that they are unique unless you recreate them (new object()). So your function passes the temp object and the called function assigns the same object to be the root. But the object itself remains the same. So if you change it, you don’t just change its value, you Operation will have impact to the whole object. This is a massive advantage since you can save much of space. So there is no need to return, that’s why you don’t process the returns in the recursion. You simply manipulate the object itself

– e.Fro
Nov 24 '18 at 16:04





One thing to keep in mind about objects in Java is that they are unique unless you recreate them (new object()). So your function passes the temp object and the called function assigns the same object to be the root. But the object itself remains the same. So if you change it, you don’t just change its value, you Operation will have impact to the whole object. This is a massive advantage since you can save much of space. So there is no need to return, that’s why you don’t process the returns in the recursion. You simply manipulate the object itself

– e.Fro
Nov 24 '18 at 16:04













This approach is called in-place, and is also used by quick sort. In the context of liked lists it is very useful to use because you don’t want to keep on creating new elements for manipulation. I hope I can help you a little bit with that. en.m.wikipedia.org/wiki/In-place_algorithm

– e.Fro
Nov 24 '18 at 16:07





This approach is called in-place, and is also used by quick sort. In the context of liked lists it is very useful to use because you don’t want to keep on creating new elements for manipulation. I hope I can help you a little bit with that. en.m.wikipedia.org/wiki/In-place_algorithm

– e.Fro
Nov 24 '18 at 16:07













I recommend using the debugger on your method, to see when the temp objects on the upper levels change. I think this will help a lot.

– e.Fro
Nov 24 '18 at 16:12





I recommend using the debugger on your method, to see when the temp objects on the upper levels change. I think this will help a lot.

– e.Fro
Nov 24 '18 at 16:12




















draft saved

draft discarded




















































Thanks for contributing an answer to Stack Overflow!


  • Please be sure to answer the question. Provide details and share your research!

But avoid



  • Asking for help, clarification, or responding to other answers.

  • Making statements based on opinion; back them up with references or personal experience.


To learn more, see our tips on writing great answers.




draft saved


draft discarded














StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53454456%2frecursion-in-merging-linked-lists%23new-answer', 'question_page');
}
);

Post as a guest















Required, but never shown





















































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown

































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown







Popular posts from this blog

Create new schema in PostgreSQL using DBeaver

Deepest pit of an array with Javascript: test on Codility

Costa Masnaga