java - Return the number of elements in a linked list recursively -


i have following recursive method in class called imagenode passed head(this - start of linked list) class called image. thought code recursively go through each node, increase count when @ end return count, unfortunatly not. going wrong?

private int countrec() {     int count = 1;     imagenode node = this;      if (node.next != null ){         node = node.next;         count++;         countrec();     }      return count; } 

you're ignoring result of countrec() - , you're iterating within recursive call, defeating purpose. (you're making recursive call on same object, no parameters , no change in state... can't good.) recursive approach based on design of:

  • if next node null, size of list 1
  • otherwise, size 1 + size next node onwards.

so:

private int countrec() {     return next == null ? 1 : 1 + next.countrec(); } 

now doesn't allow list of length 0 of course... want separate idea of list node, in case list class have like:

public int count() {     return head == null ? 0 : head.countrec(); } 

where value of head reference head node if there one, or null otherwise.

of course, o(n) in time and space. can o(1) space using iteration instead of recursion, , o(1) time keeping size of list instance variable in list, updating when need to. i'm hoping question based on educational requirement rather real code though - in production code, you'd use collections provided already.


Comments

Popular posts from this blog

php - Submit Form Data without Reloading page -

linux - Rails running on virtual machine in Windows -

php - $params->set Array between square bracket -