java - Adding nodes to end of linked list -


having trouble adding nodes end of linked code pretty self explanatory, addtoend method adds single node end of linkedlist.

public class ll5 {     // private inner class node      private class node{         int data;         node link;          public node(int x, node p){             data = x;             link = p;         }     }     // end of node class      public node head;      public ll5(){         head = null;     }      public void addtoend(int data) {         node p = head;         while (p.link != null)             p=p.link;         p.link=new node(data, null);     }       public static void main(string[] args) {         scanner input = new scanner(system.in);         ll5 list = new ll5();          list.printlist();         system.out.println("how many values want add list");         int toadd = input.nextint();          for(int = 0; < toadd; i++) {             system.out.println("enter value " + (i + 1));             list.addtoend(input.nextint());         }          system.out.println("the list is:");         list.printlist();          input.close();     }  } 

why giving me nullpointerexception error?? error somewhere in while loop in addtoend method.

you haven't handled initial condition when list has nothing , head null. because of you're getting npe.

following method should work.

public void addtoend(int data) {     node p = head;     if( p == null) {         head = new node(data, null);     } else {         while (p.link != null)             p=p.link;         p.link=new node(data, null);     } } 

Comments

Popular posts from this blog

java - nested exception is org.hibernate.exception.SQLGrammarException: could not extract ResultSet Hibernate+SpringMVC -

sql - Postgresql tables exists, but getting "relation does not exist" when querying -

asp.net mvc - breakpoint on javascript in CSHTML? -