pointers - Fix a java.lang.NullPointerException error in a queue -
this question has answer here:
- what nullpointerexception, , how fix it? 12 answers
so implemented queue in java , trying implement procedure inserts element @ end of queue.but error message "java.lang.nullpointerexception".i new @ , don't know means or how fix it.
class node { public int ielement; public string selement; public node next; public node(int iel, string sel) { ielement = iel; selement = sel; } class implement { private node head; private node tail; public implement() { head = null; tail=null; } public void insertattheend(int iel, string sel){ node newnode=new node(iel,sel); if(!empty())//if queue empty{ tail.next=newnode; tail=newnode;} else{ newnode.next=head; head=newnode; } } public static void main(string[] args) { implement k = new implement(); k.insertattheend(1, "b"); k.insertattheend(3, "bes"); k.insertattheend(4, "kes");}
you never initialize tail. if queue not empty, tail.next should point newly created node, have done. if is, though, both head , tail should point newly added node.
public void insertattheend (int iel, string sel) { node newnode = new node(iel,sel); if (!empty()) { tail.next = newnode; tail = newnode; } else { head = newnode; tail = newnode; } }
Comments
Post a Comment