LintCode 466链表节点计数
思路
遍历访问数个数
/**
* Definition of singly-linked-list:
* class ListNode {
* public:
* int val;
* ListNode *next;
* ListNode(int val) {
* this->val = val;
* this->next = NULL;
* }
* }
*/
class Solution {
public:
/**
* @param head: the first node of linked list.
* @return: An integer
*/
int countNodes(ListNode * head) {
// write your code here
int count = 0; //计数
ListNode *p = head;
while(p != NULL)
{
p = p->next;
count++;
}
return count;
}
};