【问题标题】:What's wrong with this Java Linked List representation of a stack of integers?这个整数堆栈的 Java 链表表示有什么问题?
【发布时间】:2015-10-15 03:16:05
【问题描述】:

好的,因此使用以下代码,我从 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;
 }
}

我在一个将十进制数转换为二进制数的程序中实现这一点(对于一个类)。我可以从第一个节点 AKA 链接列表的头部打印数据,但是当再次弹出时我遇到了 null 问题。

【问题讨论】:

  • 考虑提供一个runnable example 来证明您的问题。这不是代码转储,而是您正在做的事情的一个例子,它突出了您遇到的问题。这将导致更少的混乱和更好的响应
  • 注意:此类问题可以通过对应用程序进行适当的调试来发现。

标签: java linked-list stack


【解决方案1】:

如果 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;
    }

应该是

this.link = linkValue;

【讨论】:

    猜你喜欢
    • 2013-11-14
    • 2017-09-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-02-16
    • 1970-01-01
    相关资源
    最近更新 更多