i have custom linked list student
object stored node
object in it. have method, public student worststudentrec(node list)
takes head node
(list) , recursively finds node containing student
highest gpa. code below works purpose, i'm confused on whether or not can change method code works without declaring variables outside of class. example, declared private node basecase
serve node containing student
lowest gpa, , worststudent
serve eventual return variable. i'm stuck , can't figure out whether can done without declaring these variables outside of method or not. code method below. thanks!
private node basecase = new node (new student ("", double.max_value, 0)); private student worststudent; public student worststudentrec(node list) { if (list == null) return worststudent; else if (list.next == null) return worststudent; else worststudent = (basecase.data.compareto(list.data) <= 0) ? basecase.data : list.data; basecase = (basecase.data.compareto(list.data) <= 0) ? basecase : list; return worststudentrec(list.next); }
you can:
public student worststudentrec(node list) { if (list == null) return null; // add null-handling else if (list.next == null) return list.data; node theworstfromothers = worststudentrec(list.next); return (list.data.compareto(theworstfromothers.data) <= 0) ? list.data : theworstfromothers.data; }
when use recursion - keep in mind can not chain execution computation. in other words - can(and in many cases) should use result of recursion in computations.
Comments
Post a Comment