2017-02-18 180 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++; 
    }