当前位置: 面试刷题>> 链表节点计数 (经典算法题500道)


### 题目描述 给定一个单向链表的头节点 `head`,请编写一个函数来计算该链表中节点的总数。链表节点的定义如下(以Python为例,但PHP和JavaScript有类似的定义方式): ```python class ListNode: def __init__(self, val=0, next=None): self.val = val self.next = next ``` ### 函数签名 对于不同的编程语言,函数签名可能略有不同,但基本思路一致: - **Python**: `def countNodes(head: ListNode) -> int` - **PHP**: `function countNodes($head) { ... }`,其中`$head`是链表头节点的引用 - **JavaScript**: `function countNodes(head) { ... }`,其中`head`是链表头节点的引用 ### 示例代码 #### Python 示例 ```python class ListNode: def __init__(self, val=0, next=None): self.val = val self.next = next def countNodes(head: ListNode) -> int: count = 0 current = head while current: count += 1 current = current.next return count # 示例使用 node1 = ListNode(1) node2 = ListNode(2) node3 = ListNode(3) node1.next = node2 node2.next = node3 print(countNodes(node1)) # 输出: 3 ``` #### PHP 示例 ```php class ListNode { public $val = 0; public $next = null; function __construct($val = 0, $next = null) { $this->val = $val; $this->next = $next; } } function countNodes($head) { $count = 0; $current = $head; while ($current !== null) { $count++; $current = $current->next; } return $count; } // 示例使用 $node1 = new ListNode(1); $node2 = new ListNode(2); $node3 = new ListNode(3); $node1->next = $node2; $node2->next = $node3; echo countNodes($node1); // 输出: 3 ``` #### JavaScript 示例 ```javascript class ListNode { constructor(val = 0, next = null) { this.val = val; this.next = next; } } function countNodes(head) { let count = 0; let current = head; while (current !== null) { count++; current = current.next; } return count; } // 示例使用 const node1 = new ListNode(1); const node2 = new ListNode(2); const node3 = new ListNode(3); node1.next = node2; node2.next = node3; console.log(countNodes(node1)); // 输出: 3 ``` ### 码小课网站内容分享 码小课网站中包含了更多关于链表操作的详细教程和练习题,包括但不限于链表节点的插入、删除、反转、查找以及排序等算法。通过学习这些内容,你可以更加深入地理解链表这一数据结构,并掌握解决链表相关问题的技巧。欢迎大家访问码小课网站,共同学习进步!
推荐面试题