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);
     
}
}

Beware of stale-data declarations!

Here's the code revised, but I'm not sure if it will do exactly what you want.

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)
	{

		head=next1;
		item=item1;
	}

	public IntNode delete_nth(int n)
	{
		curr = head; // you probably meant to do this?
		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);
	}
}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.