we are learning about linked list using nodes and I’m not sure if i’m doing this right. We are suppose to just make a simple list but when I go to run the program, I’m getting nullpointerException pointing to showList() method but when I try to not use that method, then nothing prints out at all. Please any help is greatly appreciated.
public class node {
public int dataitems;
public node next;
node front;
public void initList(){
front = null;
}
public node makeNode(int number){
node newNode;
newNode = new node();
newNode.dataitems = number;
newNode.next = null;
return newNode;
}
public boolean isListEmpty(node front){
boolean balance;
if (front == null){
balance = true;
}
else {
balance = false;
}
return balance;
}
public node findTail(node front) {
node current;
current = front;
while(current.next != null){
//System.out.print(current.dataitems);
current = current.next;
} //System.out.println(current.dataitems);
return current;
}
public void addNode(node front ,int number){
node tail;
if(isListEmpty(front)){
front = makeNode(number);
}
else {
tail = findTail(front);
tail.next = makeNode(number);
}
}
public void printNodes(int len){
int j;
for (j = 0; j < len; j++){
addNode(front, j);
} showList(front);
}
public void showList(node front){
node current;
current = front;
while ( current.next != null){
System.out.print(current.dataitems);
current = current.next;
}
System.out.println(current.dataitems);
}
public static void main(String[] args) {
node x = new node();
x.printNodes(50);
}
}
The problem has to do with the variable scoping of your addNode method.
Your assignment of “front” only assigns the makeNode(number) value to the local variable. You need to use this.front to assign the makeNode(number) to the instance variable of your node class or refactor your variable name.