java - Implementation of a Generic Singly Linked List -
new site. trying implement generic singlylinkedlist, fetch returns null though there nodes in , delete method return false, when true expected. in addition, functions fine when decide delete in reverse order. looking set of fresh eyes see missing. thanks-in-advance.
public class singlylinkedlist<t> { private node<t> h; // list header public singlylinkedlist() { h = new <t> node(); // dummy node h.l = null; h.next = null; } public boolean insert(t newnode) { node n = new node(); genericnode node = (genericnode) newnode; if (node == null) // out of memory { return false; } else { n.next = h.next; h.next = n; n.l = (t) node.deepcopy(); return true; } } public genericnode fetch(object targetkey) { node p = h.next; genericnode node = (genericnode) p.l; // think there problem. right? while (p != null && !(node.compareto(targetkey) == 0)) { p = p.next; } if (p != null) { return node.deepcopy(); } else { return null; } } public boolean delete(object targetkey) { node q = h; node p = h.next; genericnode node = (genericnode)p.l;// think problem while (p != null && !(node.compareto(targetkey) == 0)) { q = p; p = p.next; } if (p != null) { q.next = p.next; return true; } else { return false; } } public boolean update(object targetkey, t newnode) { if (delete(targetkey) == false) { return false; } else if (insert(newnode) == false) { return false; } return true; } public void showall() { node p = h.next; while (p != null) //continue traverse list { system.out.println(p.l.tostring()); p = p.next; } } /** * * @param <t> */ public class node <t> { private t l; private node <t> next; public <t> node() { } }// end of inner class node } //end singlylinkedlist outer class
the problem lies here (in fetch
method):
genericnode node = (genericnode) p.l; // think there problem. right? while (p != null && !(node.compareto(targetkey) == 0)) { p = p.next; }
you assing node
only before entering loop, , change p
value inside loop, node
keeps initial value throughout whole loop. should use:
genericnode node = null; // define node before loop in order use later while (p != null) { node = (genericnode) p.l; // reset node value on each iteration if (node.compareto(targetkey) == 0) { break; } p = p.next; }
as have same code in delete
, same fix apply...
Comments
Post a Comment