I'm trying to create a sorted linked list without using Collections. I don't want to use Collections since I'd like to learn how to work with Linked List manually.
I'm getting NullPointer exception when I'm comparing strings and comparison <0.
Any suggestions and help are appreciated.

This is the part where the exception is triggered:

if (comp<0) 
         last.next = new Link(); //here the exception is triggered
         last.next.next = next;

Here's the full code:

class Link
   public String info;
   public Link next;                       

   public Link(String info) 
   public Link(){} 

 public class List {

    public static void main(String[] args) {
      Link list;

      list = initializelist();  

      listinsert("Shelly", ls);     
      listinsert("Mike", ls);

      System.out.println("Sorted Link List is: ");

static Link initializelist() 
           Link list = new Link();
           list.next = null;
           return list;

static void listinsert(String input, Link ls) {

Link next=null;
Link last=null;  

int comparison = input.compareToIgnoreCase(next.info);  

    last = next;            
    next = next.next;

  if (comparison==0)    

    next.info = data;
  if (comparison<0) //insert the node between 2 existing nodes
         last.next = new Link();
         last.next.next = next;

     next.next = new Link(data);
     next.next.next = null;

 static void printlist(Link ls){
   while (ls != null)
      ls = ls.next;

That implies that last is null when that line is executed, as only the last.next expression will generate an NPE. That would be the case if the while loop on lines 44-48 was executed zero times (and maybe under other circumstances as well).

Thank you. I understand where the problem occurs. I tried multiple ways to fix it, but I still get NPE. How can I avoid last.next generating NPE?

by instantiating last before you try to call a method on it.

if ( last == null ){ last = new Link(); }

is a possible way, but why calling next if there are no elements in the list yet?

Stultuske, thanks. Tried your solution, stil getting NPE.

I'm tyring to insert elements in the list in the sorted order. This part is called when the node needs to be inserted between 2 existing ones.

might have mistaken next (variable) for a method (next()), so maybe it is next that is not initialized.
try initializing that as well
but if that's the issue, I would expect an npe much sooner in your code

Edited 2 Years Ago by stultuske

This article has been dead for over six months. Start a new discussion instead.