2013-10-26 67 views
0

我试图使用类似于使用链表的StringBuilder,我想我在我的构造函数中的某个地方搞乱了。任何人都可以在这里找到问题?我相信问题在于我如何移动到下一个节点。链接的字符串列表

Node类:

private class CNode 
{ 
    private char data; 
    private CNode next; 

    private CNode(char c) 
    { 
     data = c; 
     next = null; 
    } 

    private CNode(char c, CNode nextNode) 
    { 
     data = c; 
     next = nextNode; 
    } 
} 

构造:

private CNode firstNode; 
private int length; 

public MyString(String s) 
{ 
    if(s == null) 
    { 
     this.length = 0; 
     this.firstNode = null; 
    } 
    else if(s.length() == 1) 
    { 
     this.length = 1; 
     this.firstNode.data = s.charAt(0); 
     this.firstNode.next = null; 
    } 
    else 
    { 
     this.length = s.length(); 
     CNode node = null; 
     CNode nextNode = null; 

     this.firstNode = new CNode(s.charAt(0), node); 

     for(int i = 1; i < s.length(); i++) 
     { 
      node = new CNode(s.charAt(i), nextNode); 
      node = node.next; 
     } 
    } 
} 

回答

1

这里可能有其他的问题,但考虑到这个代码块:你从来没有

else if(s.length() == 1) 
{ 
    this.length = 1; 
    this.firstNode.data = s.charAt(0); 
    this.firstNode.next = null; 
} 

公告分配为this.firstNode,这意味着您将在执行第二个时获得NullPointerException代码行。在写入节点之前尝试分配一个节点。

希望这会有所帮助!

+0

用'this.firstNode = new CNode(s.charAt(0),null)替换后两行;'? – Nealon

+0

@ Nealon-那绝对应该有帮助! – templatetypedef

+0

优秀。仍然没有解决,但解决了其他可能的问题。谢谢 – Nealon

2

一个问题,我看到的是

this.firstNode = new CNode(s.charAt(0), node); 

当该行执行,node为空,所以你firstNode结束了挂什么。此外,在您尝试构建链接的for循环中,您从不分配nextNode,但您尝试使用它将一个节点链接到下一个节点。因此,所有节点最终链接到null,初始值为nextNode

另一个问题:

this.firstNode.data = s.charAt(0); 
this.firstNode.next = null; 

这应该创建一个新的CNode,而不是因为this.firstNode仍然是空时的代码执行,这将导致一个NullPointerException。

+0

这不是那个意图吗?好像链接的字符列表以相反的顺序存储,所以第一个字符不应该指向任何东西。 (除非*不是*意图,在这种情况下,这绝对是一个问题!) – templatetypedef

+0

但我继续在以下for循环中设置节点?这不能解决这个问题吗? – Nealon

+0

@templatetypedef倒序?绝对不是意图。你怎么看? – Nealon