2011-10-14 153 views
0

我有2個關於鏈表的問題,所以我想我會發布他們在一個問題。java鏈接列表複製構造函數和字符串構造函數

首先我會從字符串

// constructor from a String 
    public CharList(String s) 
{ 
    head = head.setCharacter(s); 


} 

顯示我的節點類和拷貝構造函數和構造函數從字符串

class CharNode 
{ 

    private char letter; 
    private CharNode next; 

    public CharNode(char ch, CharNode link) 
    { 
    letter = ch; 
    next = link; 
    } 

    public void setCharacter(char ch) 
    { 
    letter = ch; 
    } 

    public char getCharacter() 
    { 
    return letter; 
    } 

    public void setNext(CharNode next) 
    { 
    this.next = next; 
    } 

    public CharNode getNext() 
    { 
    return next; 
    } 

} 

拷貝構造函數

// copy constructor 
    public CharList(CharList l) 
{ 
    CharNode pt = head; 

    while(pt.getNext() != null) 
    { 
     this.setCharacter() = l.getCharacter(); 
     this.setNext() = l.getNext(); 
    } 
} 

構造,當我嘗試編譯我得到一個錯誤,我的複製構造函數它說,它不能找到符號this.setCharacter() ...和l.setCharacter() ...

我只是在做它完全錯誤?

並與我的構造函數從字符串我知道這是錯的。我想過使用charAt(),但我怎麼知道什麼時候停止循環來做到這一點?這是一個很好的方法嗎?

任何幫助,將不勝感激。

+1

您收到答案的7個問題至今並沒有接受任何的答案。你會發現,如果你不接受好的答案,人們不太願意幫忙。 –

+0

你必須讀一點關於封裝的概念,如果你自己解決編譯問題 – Genjuro

+0

你必須接受一個答案? – alexthefourth

回答

0

您設置的字符方法可能在您的節點中,而不是在您的列表中。你還需要移動你的指針。我的意思是,你有沒有「去下一個節點」?

0

您的副本構造函數用於類CharList,而setCharacter定義在CharNode中。

this在複製構造函數中引用構造函數定義的CharList對象的當前實例。 l在您的代碼中也是CharList,而不是CharNode,它定義了setCharacter

複製構造函數應該在CharNode類中定義。

1

在您的CharList構造函數中,this指的是CharList類,它沒有setCharacter()方法(CharNode)。另外,當你在java中調用一個方法時,你需要傳遞參數,例如setFoo(newFoo),不setFoo() = newFoo

+0

我可以說類似CharNode.setCharacter(paramater)嗎? – alexthefourth

+0

這是基本的想法,雖然你通常會使用CharNode的實例,而不是類本身。 – jtahlborn

0

在你的「拷貝構造函數」你需要去通過列表中,其頭部開始傳遞,併爲您的新列表創建新的節點......

public CharList(CharList l) 
{ 
    // Whatever method your CharList provides to get the 
    // first node in the list goes here 
    CharNode pt = l.head(); 

    // create a new head node for *this* list 
    CharNode newNode = new CharNode(); 
    this.head = newNode; 

    // Go through old list, copy data, create new nodes 
    // for this list. 
    while(pt != null) 
    { 
     newNode.setCharacter(pt.getCharacter()); 
     pt = pt.getNext(); 
     if (pt != null) 
     { 
      newNode.setNext(new CharNode()); 
      newNode = newNode.getNext(); 
     } 

    } 
} 

至於從String ...相同的概念創建列表,除非你通過遍歷字符串,而不是另一個CharList

for (int i = 0; i < myString.length(); i++) 
{ 
    ... 
    newNode.setCharacter(myString.charAt(i)); 
    ... 
+0

字符串有長度嗎?它是否像一個數組有長度? – alexthefourth

+0

字符串是字符數組。 – DarthVader

+0

我必須在構造函數內創建一個新的charnode,是嗎? – alexthefourth