-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