2016-11-15 33 views
0

我需要为我的整数数组创建一个单链表,但是,我不知道现在我的代码有什么错误。为什么我无法从数组创建单个链接的列表?

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

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行得到错误信息

+0

它不起作用?你怎么知道的? – shmosel

+0

我尝试过运行它 – joeymed

+0

@shmosel很有趣 –

回答

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; 
    } 
} 
+0

这段代码是不是表示在循环之前我的head = null(除了null之外,没有任何内容在列表中)。那么当我开始循环整数值null将被移动到右侧? OHH还是这意味着我的下一个头(头是指列表的开头是吧?)我基本上说下一个值是空的吗? – joeymed

+0

是的,当您创建每个新节点时,下一个值默认为'null'。链表是如何工作的,它必须在某个地方结束。尝试一下代码,然后回到这里评论。 –

+0

我试过给出的代码,但似乎有一个错误:不兼容的源代码 - 错误的sym类型:sllset.SLLSet.SLLNode。在curr.next = SLLNode(sortedArray [i],null)。编辑:没关系,我通过在它前面添加新来修复它。似乎已经修复了它 – joeymed

相关问题