计算链表中有多少个节点.
样例
给出 1->3->5
, 返回 3
.
1 /** 2 * Definition of ListNode 3 * class ListNode { 4 * public: 5 * int val; 6 * ListNode *next; 7 * ListNode(int val) { 8 * this->val = val; 9 * this->next = NULL; 10 * } 11 * } 12 */ 13 14 15 class Solution { 16 public: 17 /* 18 * @param head: the first node of linked list. 19 * @return: An integer 20 */ 21 int countNodes(ListNode * head) { 22 // write your code here 23 int count = 0; 24 while (head->next) { 25 count++; 26 head = head->next; 27 } 28 return count; 29 } 30 };