解答
getLength方法
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | /** * 统计单链表的节点的个数(不计算头节点) * * @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; } |
测试
1 2 | //测试一下求单链表中有效节点的个数 System.out.println( "有效节点的个数为:" +getLength(singleLinkedList.getHead())); |
帖子还没人回复快来抢沙发