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

标签 java linked-list stack

好的,通过下面的代码,我从 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/

相关文章:

java - 尝试运行 Apache-Tomcat : JRE_HOME variable is not defined correctly 的 startup.bat 时出错

java - 如何从连接池中删除损坏的连接对象?使用c3p0

java - "else"不工作

java - 如何从DB和JTable中删除选定的行?

C - 赋值后访问结构体属性会导致段错误

c++ - 如何在链接列表中创建链接列表?

c - 段错误 - 链表 (UNIX)

c++ - 多位后缀表达式

c++ - 无法使用 OOP C++ 打印堆栈项

python - 在 Python 中使用堆栈计算中缀表达式 : I cant find my error