/**
* Definition of ListNode
* 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) {
if(head == NULL)
{
return 0;
}
else
{
int i = 0;
for(;head != NULL;head = head->next)
{
i++;
}
return i;
}
}
};Lintcode 入门-466. 链表节点计数
本文介绍了一种通过遍历链表来计算链表中节点数量的方法。定义了一个链表节点类ListNode,并实现了一个名为countNodes的函数,该函数接受链表头节点作为参数并返回链表中的节点总数。

被折叠的 条评论
为什么被折叠?



