Reputation: 31
Okay, so with the following code I get a nullpointer exception from everything in my pop method. Therefore, I know that 'head' must be null when that method runs. Thing is I have no idea why and I've looked over my code a good bit now. Please help!
Here it is:
NODE CLASS:
public class StackNode{
private StackNode link; //link to next node
private int value;
public StackNode(int value, StackNode linkValue){
this.link = link;
this.value = value;
}
public StackNode(){
this.link = null;
}
public void setNodeData(int value){
this.value = value;
}
public void setLink(StackNode newLink){
this.link = newLink;
}
public int getValue(){
return this.value;
}
public StackNode getLink(){
return link;
}
}
LINKED LIST CLASS:
public class IntStackList{
private StackNode head;
public IntStackList(){ this.head = null; }
public void push(int value){
this.head = new StackNode(value, head);
}
public int pop(){
int value = this.head.getValue(); //get the int value stored in the head node
this.head = head.getLink(); //sets the head to the next node in line
return value;
}
}
I am implementing this in a program that converts a decimal number to binary(for a class). I can print data from the first node AKA the head of the linked list but then I have the null issue when popping again.
Upvotes: 0
Views: 69
Reputation: 347204
You're assigning link
to itself in the constructor if the StackNode
...
public class StackNode {
private StackNode link; //link to next node
private int value;
public StackNode(int value, StackNode linkValue) {
this.link = link;
this.value = value;
}
It should be
this.link = linkValue;
Upvotes: 2