需要帮助将我的for循环更改为while循环

时间:2017-02-18 01:38:07

标签: java loops

我的代码的当前输出有效,但我想将最后一个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的数字列表,我希望输出相同,但我不知道如何将底部for循环更改为while循环而不更改输出 感谢

2 个答案:

答案 0 :(得分:0)

将循环更改为while循环。

unsafeFreeze

答案 1 :(得分:0)

鉴于您的链接列表不是循环链接列表,当您在最后一个节点上呼叫getNext()时,它将返回null

LinearNode<Integer> current = head;

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

这样,如果您的列表为空,您还可以避免NullPointerException