Can someone please help me find out why I am getting a nullpointerexception for this code. Ive been racking my brain and cant find it for the life of me. The program is supposed to delete an element from the linked list that is built in the main method and then display the updated list.
import java.util.*;
public class IntNode
{
public int item; //element in list
public IntNode next; //next node in list
public IntNode head; //reference to first node in list
//////Constructor///////
public IntNode(int item1, IntNode next1)
{
item=item1;
next=next1;
}
public void delete_nth(int n)
{
IntNode prev;
IntNode curr = head;
while(curr != null && n > curr.item)
{
if(curr.next==null)
System.out.println("error: out of bounds");
else
{
prev = curr; //go to next link
curr = curr.next;
}
}
if(head.item==n)
head = curr.next;
else
prev = curr.next;
}
public static void main(String [] args)
{
int n;
//Declare a list
IntNode list = new IntNode(0, new IntNode(1, new IntNode(2, new IntNode(3, new IntNode
(4, new IntNode(5, new IntNode(6, new IntNode
(7, new IntNode(8, null)))))))));
Scanner sc = new Scanner(System.in);
System.out.println("number of the element to delete: ");
n=sc.nextInt();
list.delete_nth(n);
System.out.println("result" + list);
}
}