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

Java 需要帮助将我的for循环更改为while循环吗,java,loops,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 LinearNo

代码的当前输出正常,但我想将最后一个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();
    }
}
公共类BuildLinkedList{
公共静态void main(字符串[]args){
//创建包含1、2、…、10的链接列表
//从10开始,将每个节点添加到列表的开头
LinearNode head=null;//创建空链表
线性节点;
对于(int i=10;i>=1;i--)
{
//为i创建一个新节点
intNode=新的线性节点(新的整数(i));
//将其添加到链接列表的开头
intNode.setNext(head);
head=intNode;
}
//遍历列表并显示每个数据项
//电流将指向每个连续节点,从第一个节点开始
线性节点电流=磁头;

for(int i=1;i将for循环更改为while循环

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

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

LinearNode<Integer> current = head;

while(current != null)
{
    System.out.println(current.getElement());
    current = current.getNext();
}
LinearNode电流=磁头;
while(当前!=null)
{
System.out.println(current.getElement());
current=current.getNext();
}

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

为什么您希望代码“更通用”在这种情况下?如果有一个定义的迭代范围,For循环是完全可以的。将
For
循环替换为
while
循环只会降低此处的可读性。人们非常熟悉您使用的习惯用法,因此偏离它只会让人们不得不更仔细地观察。