-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循环而不更改我的输出 谢谢
为什么你希望你的代码在这种情况下是“更一般的”? For循环完全没问题,当你有一个定义的范围,你将迭代。 – nbro
用'while'循环替换'for'循环只会降低可读性。人们对你使用的成语非常熟悉,所以偏离它只会让人们看得更近。 – 4castle