
/**
* 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) {
if (head==null) return 0;
ListNode cur = head;
int count = 1;
while (cur.next != null){
cur = cur.next;
count++;
}
return count;
}
}
留言