Linked list recursion in Java -
i have code recursive method iterates through linked list , returns number of integers positive. here question:
the method countpos below must recursive method takes node head argument, goes downwards list headed head, , counts number of nodes have positive info field.
the code have works however, don't understand how works.
public int countpos(node head) { int count = 0; if (head == null) { homecoming count; } if (head.data > 0) { count++; homecoming count + countpos(head.next); } else { homecoming count + countpos(head.next); } } the problem i'm having don't understand how count doesn't set 0 every time method called. reason statement int count = 0; ignored next time method gets called. because i'm returning count also? explanation appreciated.
thanks.
each time phone call countpos(), new version of function starts. function starts clean slate meaning of local variables (count) own, , no other "copy" of countpos can see or modify local variables.
the state passed between these "copies" or of countpos variables passed in parameters (node head).
so here's rough workflow assuming list [1, -2, 3]
countpos starts, , says number of positive nodes equal 1, since "1" positive. total number of positive nodes equal 1 + whatever next function returns. the next function says number of positive nodes equal 0 + whatever next function returns. the next function says number of positive nodes equal 1 + whatever next function returns the next function sees head == null , returns 0. now each recursive function returns 1 after original function called it, total number of positive nodes "snowballing" return.
the total number returned in end 2.
java recursion
No comments:
Post a Comment