【问题标题】:Why can't I create a singly linked list from an array? [duplicate]为什么我不能从数组创建单链表? [复制]
【发布时间】:2017-03-28 21:31:44
【问题描述】:

我需要为我的整数数组创建一个单链表,但是,我现在不知道我的代码目前有什么问题。

这是创建节点的代码。 (数据)

package sllset;

class SLLNode {
    int value;
    SLLNode next;

public SLLNode(int i, SLLNode n){
    value = i;
    next = n   
    }   
}

具有我的方法和构造函数的其他类看起来像这样。

package sllset;


public class SLLSet {
    private int setSize;
    private SLLNode head;

public SLLSet(){
    head = null;
    setSize = 0;
}

public SLLSet(int[] sortedArray){ //second constructor
    setSize = sortedArray.length;
    int i;
    head=null;
    for(i=0;i<setSize;i++){
        head.next = head;
        head = new SLLNode(sortedArray[i],head.next);    
    }
}


public String toString(){
    SLLNode p;
    String result = new String();
    for(p=head ; p!=null ; p=p.next)
        result += p.value;
    return result;
}

public static void main(String[] args) {
int[] A = {2,3,6,8,9};
SLLSet a = new SLLSet(A);
System.out.println(a.toString());

    }

}

我的问题是我的第二个构造函数不起作用,我真的不知道为什么。我一直在关注如何制作大多数这些功能的指南,所以我对代码的了解不足以破译问题。

编辑:所以有人告诉我指定我在第 19 行得到 NULLPointerException 的问题;我在哪里编码 head.next = head; .然而,当 我删除那部分进行测试,第 20 行收到错误消息

【问题讨论】:

  • 它不起作用?你怎么知道的?
  • 我试过运行它
  • @shmosel 很有趣
  • 它在第 19 行给了我一个空指针异常:所以我把 head.next = head.当我取出它时,第 20 行出现错误。
  • 宾果游戏!请将其包含在问题中。

标签: java linked-list nodes singly-linked-list


【解决方案1】:

让我们看看这个

head=null;     // you are setting head to null
for(i=0;i<setSize;i++){
    head.next = head;  // see two lines up, head is null, it can not have next

您的构造函数有一些问题。尝试使用此版本:

public SLLSet(int[] sortedArray){ //second constructor
    head = null;
    if (sortedArray == null || sortedArray.length == 0) {
        setSize = 0;
    }
    setSize = sortedArray.length;
    head = new SLLNode(sortedArray[0], null);
    SLLNode curr = head;

    for (int i=1; i < setSize; ++i) {
        curr.next = new SLLNode(sortedArray[i], null);
        curr = curr.next;
    }
}

【讨论】:

  • 代码是否意味着在循环之前我的 head = null (除了 null 之外,列表中没有任何内容)。那么当我开始循环整数时,值 null 会向右移动吗?哦,或者这是否意味着我的下一个头(头意味着列表的开头对吗?)我基本上说下一个值再次为空?
  • 是的,当您创建每个新节点时,下一个值默认为null。这就是链表的工作方式,它必须在某个地方结束。试试代码,然后用 cmets 回到这里。
  • 我尝试了给出的代码,但似乎有一个错误:不兼容的源代码 - 错误的符号类型:sllset.SLLSet.SLLNode。在 curr.next = SLLNode(sortedArray[i],null)。编辑:没关系,我通过在它前面添加新来修复它。好像修好了
  • 我想我通过为它分配内存来修复它。
  • curr.next = new SLLNode(sortedArray[i],null);
猜你喜欢
  • 2016-03-08
  • 2010-12-01
  • 2011-07-19
  • 2016-06-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多