466. 链表节点计数

/**
 * 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;

        int count = 0;
        while (head != null) {
            head = head.next;
            count++;
        }

        return count;
    }
}
12-25 21:13