有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java需要帮助将我的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的数字列表,我希望输出是相同的,但我不确定如何在不更改输出的情况下将底部for循环更改为while循环 谢谢


共 (2) 个答案

  1. # 1 楼答案

    假设你的链表不是循环链表,当你在最后一个节点上调用getNext()时,它将返回null

    LinearNode<Integer> current = head;
    
    while(current != null)
    {
        System.out.println(current.getElement());
        current = current.getNext();
    }
    

    这样,如果列表为空,也可以避免NullPointerException

  2. # 2 楼答案

    将for循环更改为while循环

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