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 ...