试题
考点

数据结构-链表-单向链表

面5笔5

求单链表中有效节点的个数

前往“校招VIP”小程序,刷题更快
最新校招难题刷题,快来进刷题群吧
解答

getLength方法

/**
* 统计单链表的节点的个数(不计算头节点)
*
* @param head 链表的头节点
* @return 有效节点的个数
*/
public static int getLength(HeroNode head) {
//空链表则返回长度为0
if (head.next == null) {
return 0;
}
int length = 0;
HeroNode cur = head.next;
while (cur != null) {
length++;
//遍历
cur = cur.next;
}
return length;
}

测试

//测试一下求单链表中有效节点的个数
System.out.println("有效节点的个数为:"+getLength(singleLinkedList.getHead()));


文章链接

评论
暂无评论

加载更多