1
如何解決包含遍歷節點的while循環的Big-O問題,並且只要它不等於null就增加長度?這隻會是O(N)
,因爲它通過N個節點?此外,while循環中的語句只是O(1)
,是正確的嗎?Big-O for while循環?
/**
*@param head the first node of the linked list
*@return the length of the linked list
*/
public static <E> int getLength(Node<E> head) {
int length = 0;
Node<E> node = head;
while (node!=null) {
length++;
node = node.next;
}
return length;
}