这个 Java 整数堆栈的链表表示有什么问题?
What's wrong with this Java Linked List representation of a stack of integers?
好的,所以使用下面的代码,我从我的 pop 方法中的所有内容中得到了一个空指针异常。因此,我知道 'head' 在该方法运行时必须为空。事情是我不知道为什么,我现在已经仔细检查了我的代码。请帮忙!
Here it is:
节点 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;
}
}
链接列表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;
}
}
我正在一个将十进制数转换为二进制数的程序中实现这个(对于 class)。我可以从第一个节点 AKA 链表的头部打印数据,但是当再次弹出时我遇到了空问题。
如果 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;
好的,所以使用下面的代码,我从我的 pop 方法中的所有内容中得到了一个空指针异常。因此,我知道 'head' 在该方法运行时必须为空。事情是我不知道为什么,我现在已经仔细检查了我的代码。请帮忙!
Here it is:
节点 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;
}
}
链接列表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;
}
}
我正在一个将十进制数转换为二进制数的程序中实现这个(对于 class)。我可以从第一个节点 AKA 链表的头部打印数据,但是当再次弹出时我遇到了空问题。
如果 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;