2017-02-18 182 views
-2

我的代碼的電流輸出工作,但我想改變的最後一個for循環進入while循環,因爲它更普遍需要幫助改變我的for循環變成一個while循環

繼承人我的代碼

public class BuildLinkedList { 

public static void main(String[] args) { 

    // create a linked list that holds 1, 2, ..., 10 
    // by starting at 10 and adding each node at head of list 

    LinearNode<Integer> head = null; //create empty linked list 
    LinearNode<Integer> intNode; 

    for (int i = 10; i >= 1; i--) 
    { 
     // create a new node for i 
     intNode = new LinearNode<Integer>(new Integer(i)); 
     // add it at the head of the linked list 
     intNode.setNext(head); 
     head = intNode; 
    } 

    // traverse list and display each data item 
    // current will point to each successive node, starting at the first node 

    LinearNode<Integer> current = head; 
    for (int i = 1; i <= 10; i++) 
    { 
     System.out.println(current.getElement()); 
     current = current.getNext(); 
    } 
} 

}

輸出只是打印1-10的數字列表,我希望輸出是相同的,但我不知道如何將底部的循環更改爲while循環而不更改我的輸出 謝謝

+0

爲什麼你希望你的代碼在這種情況下是「更一般的」? For循環完全沒問題,當你有一個定義的範圍,你將迭代。 – nbro

+0

用'while'循環替換'for'循環只會降低可讀性。人們對你使用的成語非常熟悉,所以偏離它只會讓人們看得更近。 – 4castle

回答

0

鑑於你的鏈表是不是圓的鏈表,當你在最後一個節點上稱之爲getNext()它會返回null

LinearNode<Integer> current = head; 

while(current != null) 
{ 
    System.out.println(current.getElement()); 
    current = current.getNext(); 
} 

這樣,如果列表爲空,您也將避免NullPointerException

0

將循環更改爲while循環。

int i = 1; 
    while(i <= 10) 
    { 
     System.out.println(current.getElement()); 
     current = current.getNext(); 
     i++; 
    }