I am trying to write a program that will delete the nth element from a linked list. Before I was getting a nullpointerexception but I think I cleared that up. Now I just get a repeating error message that I put in the code for when the list goes to the end and is null(error: out of bounds). Can anyone tell me where I went wrong?
import java.util.*;
public class IntNode1
{
public int item;
public IntNode1 next;
public IntNode1 head;
IntNode1 prev = null;
IntNode1 curr = head;
//////Constructor///////
public IntNode1(int item1, IntNode1 next1)
{
head=next1;
item=item1;
}
public void delete_nth(int n)
{
curr = head;
while(curr.item != n && 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(curr == head)
head = head.next;
else
prev.next = curr.next;
}
public static void main(String [] args)
{
int n;
//Declare a list
IntNode1 list1 = new IntNode1(1, new IntNode1(2, new IntNode1(3, new IntNode1
(4, new IntNode1(5, new IntNode1(6, new IntNode1
(7, new IntNode1(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);
}
}