java - Getting nullpointer exception in the last node of singlylinked list -
public class node { public string name; public node next; public node(string name, node next ){ this.name = name; this.next = next; } public string getname(){ return name; } public void setname(string n){ name = n; } public node getnext(){ return next; } public void setnext(node n){ next = n; } public string tostring() { return "name " + name; } } public class linkedlist { node head = null; int nodecount= 0; int counter = 0; linkedlist(){ head = null; } public boolean isempty(){ return (head != null); } public void insertnode( string name ){ if( head == null){ head = new node(name, null); nodecount++; }else{ node temp = new node(name, null); temp.next = head; head = temp; nodecount++; } } public node reversetest(node l){ if(l == null || l.next ==null){ return l; } node remainingnode = reversetest(l.next); node cur = remainingnode; while(cur.next !=null){ cur=cur.next; } l.next = null; cur.next = l; return remainingnode; } public boolean searchlinkedlist(node l, string s){ if (l == null) return false; else{ while(l !=null){ if(s.equals(l.name)) return true; l= l.next; } } return false; } public string tostring(){ node current = head; string output = ""; while(current !=null){ output += "[" + current.getname() + "]"; current = current.getnext(); } return output; } } public class linkedlistdemo { public static void main(string[] args){ linkedlist friendlist = new linkedlist(); friendlist.insertnode("first"); friendlist.insertnode("second"); friendlist.insertnode("third"); friendlist.insertnode("fourth"); friendlist.searchlinkedlist(friendlist.head, "hello"); string namelist = friendlist.tostring(); system.out.println(namelist); system.out.println("finish"); } }
i have singly linked list. wanted search value not present in linkedlist , in last loop when reaches l = l.next receive npe. don't see mistake here. please point right direction.
as pointed out in comments, there no errors. ide showing last reading of these properties.
when last loop here:
public boolean searchlinkedlist(node l, string s){ if (l == null) return false; else{ while(l !=null){ if(s.equals(l.name)) return true; l= l.next; } } return false; }
l indeed equal null; means when ide tries read properties (name , next), (and it, not program's actual output) gets reasonable nullpointerexception.
the program otherwise runs fine.
Comments
Post a Comment