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)
{this.info=info;}
public Link(){}
}
public class List {
public static void main(String[] args) {
Link list;
list = initializelist();
listinsert("Jack",ls);
listinsert("Andy",ls);
listinsert("Shelly", ls);
listinsert("Mike", ls);
System.out.println("Sorted Link List is: ");
printlist(ls);
static Link initializelist()
{
Link list = new Link();
list.info="Jack";
list.next = null;
return list;
}
static void listinsert(String input, Link ls) {
Link next=null;
Link last=null;
next=ls;
int comparison = input.compareToIgnoreCase(next.info);
while((next.next!=null)&&(comparison>0))
{
last = next;
next = next.next;
}
if (comparison==0)
{
next.info = data;
}
else{
if (comparison<0) //insert the node between 2 existing nodes
{
last.next = new Link();
last.next.next = next;
}
else
{
next.next = new Link(data);
next.next.next = null;
}
}
}
static void printlist(Link ls){
while (ls != null)
{
System.out.println(ls.info);
ls = ls.next;
}
}
}