/** * 获取链表的节点个数 * @param {ListNode} head - 链表的头节点 * @return {number} - 链表的节点个数 */ export const getListLength = function (head) { let count = 0; // 初始化计数器 let current = head; // 初始化当前节点为链表头 // 遍历整个链表,直到链表末尾 while (current !== null) { count++; // 每遍历一个节点,计数器加一 current = current.next; // 移动到下一个节点 } return count; // 返回链表的长度 }; /** * 链表节点 * @param {*} val * @param {*} next */ export function ListNode(val, next) { this.val = (val === undefined ? 0 : val); this.next = (next === undefined ? null : next); }