Hi, I am trying to write a code that will delete an element from a linked list and then display the updated list, but I keep getting a nullpointerexception, does anyone know where I went wrong?
import java.util.*;
public class IntNode
{
public int item;
public IntNode next;
public IntNode head;
IntNode prev = null;
IntNode curr = head;
//////Constructor///////
public IntNode(int item1, IntNode next1)
{
item=item1;
next=next1;
}
public IntNode delete_nth(int n)
{
while(curr.item != n && n > curr.item)
{
if(curr.next==null)
return null;
else
{
prev = curr; //go to next link
curr = curr.next;
}
}
if(curr == head)
head = head.next;
else
prev.next = curr.next;
return curr;
}
public static void main(String [] args)
{
int n;
//Declare a list
IntNode list1 = 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();
list1.delete_nth(n);
System.out.println(list1);
}
}