java - size of linkedList -
i'm new java, , given linkedlist set-up, need use recursion or while loop write size function return size of linkedlist. guess i'm confused how size function when linkedlist setup doesn't initialize node, head etc.
package list; public class linkedlist { public int value; public linkedlist next; public linkedlist (int value, linkedlist next) { this.value = value; this.next = next; } public static linkedlist list () { return new linkedlist(1, new linkedlist(2, new linkedlist(3, null))); } public int size () { int size = 0; node current = head; while(current.next != null) { current = current.next; size++; } return size; } }
in current formulation, linkedlist
instances nodes lists. that's ok, means there no distinguished "head" of list ...
in context, fix change:
node current = head;
to
linkedlist current = this;
(and, yes, size
variable should start 1
. in formulation, empty list represented null
. if calling size()
on instance of linkedlist
, size of list must @ least 1.)
@konrad states "a list should encapsulate nodes."
actually design choice. if following oo design principles should. however, there situations pragmatically don't want that. necessary "sacrifice" abstraction better performance or reduce memory utilization.
Comments
Post a Comment