java - Linked list creates infinte loop when outputted (No Iterators allowed) -
when user stores 2 or more values list, output displays this:
item 3: null item 4: null item 5: null ... item 14623: null
this case when user wants output list
case output: { system.out.println ("the list:"); displaylist(); break; }
which leads displaylist() method
public static void displaylist() { (int = 0; <= list.size (); i++) { system.out.println ("item " + + ": " + list.get(i)); } }
which uses list.size()
public int size() { for(node n = header; n.getnext() != null; n = n.getnext()) { size++; } return size; }
and list.get()
public object get(int index) { node n = traverse(index); if (n == null) { return null; } return n.getdata(); }
getnext()
public node getnext() { return next; }
traverse(). think method what's causing problems
public node traverse(int index) { node n = header; if (index < 0) { return null; } (int indextwo = 0; indextwo < index; indextwo++) { if (n == null) { return null; } // end of if (n == null) n = n.getnext (); } return n; }
this part never executed:
for (int indextwo = 0; indextwo < index; indextwo++)
since index
variable 0
, indextwo < index
gives false
. use:
for (int indextwo = 0; indextwo <= index; indextwo++)
edit:
another issue in size()
method:
public int size() { for(node n = header; n.getnext() != null; n = n.getnext()) { size++; } return size; }
where increment size
variable static? one. so, must have initialized elsewhere. guess need make local variable , initialize inside method. issue getnext()
twice in each step:
for(node n = header; n.getnext() != null; n = n.getnext())
just check n
not n.getnext() != null
null
.
Comments
Post a Comment