这个整数堆栈的 Java 链表表示有什么问题?



好的,所以通过下面的代码,我从我的 pop 方法中的所有内容中得到一个 nullpointer 异常。因此,我知道当该方法运行时,"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;

最新更新