954,506 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

nullpointerexception

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

}
}

JConnor135
Newbie Poster
18 posts since Jul 2008
Reputation Points: 10
Solved Threads: 0
 

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);
	}
}
Alex Edwards
Posting Shark
972 posts since Jun 2008
Reputation Points: 392
Solved Threads: 109
 

This article has been dead for over three months

Post: Markdown Syntax: Formatting Help
You