Question:
Null Pointer Exception?
Raitei
2009-08-30 15:17:30 UTC
I keep getting a null pointer exception. I think it has something to do with the InsertAtEnd Method and the Delete method, however im not sure


package linkedlist;

public class LinkedList {
private class node{
int data;
node next;

}

private node first;//pointer to the first node in the list

public LinkedList(){ //create an empty linked list
first = null;
}

public boolean empty(){ // return true if the list is empty, otherwise return false
if(first == null){
return true;
}else
return false;
}

public void InsertinFront(int x){//insert a value x in front of the list
node newptr = first;
newptr = new node();
newptr.data = x;
newptr.next = first;
first = newptr;
}

public void InsertAtEnd (int x) {
node last = first;
while(last != null) {
last = last.next;
}
node newptr = new node();
newptr = last.next;
newptr.next = null;
newptr.data = x;

}

public void Delete(int x){//if value x is in the list, remove x
node dptr = first;
node preptr = first;
while(dptr.data != x){
dptr = dptr.next;
}

preptr.next = dptr.next;

}

public void Display(){// Display the data values in the linked list
node p = first;
while(p != null){
System.out.print(p.data + " ");
p = p.next;
}
System.out.println();

}

public int count(){//Count and return the number of values in the linked list
int count = 0;
node p = first;
while(p != null){
count++;
p = p.next;
}
return count;
}

public static void main(String[] arg){
LinkedList X = new LinkedList();

for(int a = 1; a < 10; a++){
if((a % 2) == 0)
X.InsertAtEnd(a);
}
X.Display();

X.InsertinFront(0);
System.out.println("list after inserting 0:");
X.Display();

X.Delete (2);
System.out.println ("list after deleting 2:");
X.Display();

X.Delete(6);
System.out.println ("list after deleting 6:");
X.Display();

if(!X.empty())
System.out.println("List is not empty.");

System.out.println("Number of values:"+ X.count());
}//main

}//class
Three answers:
Alex Maureau
2009-08-30 15:51:48 UTC
The last pointer is always pointing to null (it's next element). This is why you are getting the exception.
wilcoxen
2016-12-01 02:24:43 UTC
line 129.ArrayListf4e18829d4ed4c672887bbdf7f84d testCards; // errors is via the fact it incredibly is on no account assigned to an instantiation of an ArrayListf4e18829d4ed4c672887bbdf7f84d... the two call a function to create one or use the recent operator... i'm guessing you meant to initialize this with some thing in the previous you reached line one 0 one.
Blackcompe
2009-08-30 15:58:09 UTC
public void InsertAtEnd (int x) {

if(first == null) {

first = new node();

first.data = x;

return;

}

node elem = first;

while(elem.next != null) {

elem = elem.next;

}

elem.next = new node();

elem.next.data = x;

}


This content was originally posted on Y! Answers, a Q&A website that shut down in 2021.
Loading...