2015-09-26 45 views
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; 
} 

回答

2

正如你所說的,遍歷鏈表需要O(N),因爲你需要遍歷每個節點一次。

賦值運算符爲O(1),因爲每次只需要執行一次。