好的,通过下面的代码,我从 pop 方法中的所有内容中得到了一个空指针异常。因此,我知道该方法运行时“head”必须为空。问题是我不知道为什么,我现在已经仔细检查了我的代码。请帮忙!
Here it is:
节点类别:
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;
}
}
链接列表类:
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;
}
}
我正在一个将十进制数转换为二进制(对于一个类)的程序中实现这一点。我可以从第一个节点(又称链表头)打印数据,但再次弹出时出现空问题。
最佳答案
如果 StackNode
...,则您将在构造函数中将 link
分配给自身
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;
}
应该是
this.link = linkValue;
关于java - 这个整数堆栈的 Java 链表表示有什么问题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33139232/