2016-02-29 74 views
1

我的目標是製作一個鏈接列表,其中每個鏈接都是一個字符。我希望它將一個字符串作爲參數,取第一個字母並將其轉換爲一個char,然後將其餘的字符串傳遞到下一個鏈接,直到整個字符串被存儲爲止。這是我迄今爲止,雖然我不確定它的哪些部分是正確的或不正確的。我查了一堆例子,這似乎是默認設置。我很難實現我的鏈表類

public class linkedChar{ 

    char data; 
    linkedChar head; 
    linkedChar next; 

    //This is the empty link constructor 
    public linkedChar(){ 
     next = null; 
    } 
    //This is the constructor that takes a string 
    public linkedChar(String input){ 
     if(input.length() > 0){ 
      data = input.charAt(0); 
      next = new linkedChar(input.substring(1)); 
     } 
    } 
} 

該代碼編譯但它不能與我的其他操作方法一起工作。例如,我的長度方法。

public int length(){ 
    int length = 0; 
    linkedChar curr = head; 
    while(curr != null){ 
     curr = curr.next; 
     length++; 
    } 
    return length; 
} 

使用時,返回的長度始終爲0。我不知道這部分代碼有錯誤,我不知道如何解決它。任何幫助將是偉大的,謝謝。

回答

0

在你的構造函數,你永遠初始化head任何位置,因此在你的長度的方法,當你設置linkedChar curr = head;你設置curr爲null,從而length從來沒有在while循環被遞增。

+0

哦,呵呵,這是有道理的。謝謝!我能解決這個問題。 – rimbleysucksatjava

1

在構造函數head = null,然後在length方法linkedChar curr = null;因此長度永遠不會增加並保持爲零。因爲while循環不符合輸入條件。

+0

謝謝!我修好了它。 – rimbleysucksatjava

0

您所遇到的問題歸功於linkedChar head;,因爲Java編譯器會爲您設置零值(即將其設置爲null)。因此,您的length()函數將始終在第一輪停止。

一個快速解決方法是簡單地放棄linkedChar head字段並將length()函數中的linkedChar curr設置爲next。這將解決您的問題。

即使您的代碼如下

class Linked{ 

    char data; 
    Linked next; 

    //This is the empty link constructor 
    public Linked(){ 
    next = null; 
    } 
    public int length(){ 
    int length = 0; 
    Linked curr = next; 
    while(curr != null){ 
     curr = curr.next; 
     length++; 
    } 
    return length; 
    } 

    //This is the constructor that takes a string 
    public Linked(String input){ 
    if(input.length() > 0){ 
     data = input.charAt(0); 
     next = new Linked(input.substring(1)); 
    } 
    } 
} 

public class LinkedChar { 
    public static void main(String[] args) { 
    Linked l = new Linked("abcd"); 
    // Here it will print out 4 
    System.out.println(l.length()); 
    } 
} 

好運。

+0

謝謝,這是我最終做的。 – rimbleysucksatjava