466. 链表节点计数

2017-12-05  本文已影响0人  叨逼叨小马甲

计算链表中有多少个节点.
样例
给出 1->3->5, 返回 3.

import LintClass.ListNode;

/**
 * Definition for ListNode.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int val) {
 *         this.val = val;
 *         this.next = null;
 *     }
 * }
 */


public class CountNodes_466 {
    static int sum = 0;
    /*
     * @param head: the first node of linked list.
     * @return: An integer
     */
    public static int countNodes(ListNode head) {
        if(head == null)
            return 0;
        else {
            if(head.next != null ) {
                sum++;
                countNodes(head.next);
            }
            return sum;
        }
        
        // write your code here
    }
    
    public static void main(String[] args) {
        int start = 10;
        ListNode node1 = new ListNode(start);
        ListNode node2 = new ListNode(9);
        ListNode node3 = new ListNode(8);
        node1.next = node2;
        node2.next = node3;
        countNodes(node1);
        System.out.print(sum);
    }
}
上一篇 下一篇

猜你喜欢

热点阅读