数据结构—线性结构—链表:(链表节点计数)
一、题目:计算链表中有多少个节点.
样例:给出
1->3->5, 返回 3.二、代码:
/**
* Definition for ListNode
*/
public class ListNode {
int val;
ListNode next;
ListNode(int x) {
val = x;
next = null;
}
}
public class Solution {
/**
* @param head: the first node of linked list.
* @return: An integer
*/
public int countNodes(ListNode head) {
int i = 0;
while(head != null){
i++;
head = head.next;
}
return i;
}
}

本文介绍了一种简单有效的算法来计算链表中节点的数量。通过遍历链表并逐个计数节点的方式,该算法能够高效地得出链表长度。示例代码展示了如何实现这一算法。
786

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



