LintCode 466链表节点计数

题目描述

思路
遍历访问数个数

/**
 * Definition of singly-linked-list:
 * class ListNode {
 * public:
 *     int val;
 *     ListNode *next;
 *     ListNode(int val) {
 *        this->val = val;
 *        this->next = NULL;
 *     }
 * }
 */

class Solution {
public:
    /**
     * @param head: the first node of linked list.
     * @return: An integer
     */
    int countNodes(ListNode * head) {
        // write your code here
        int count = 0;  //计数
        ListNode *p = head;
        while(p != NULL)
        {
            p = p->next;
            count++;
        }
        return count;
    }
   
};

猜你喜欢

转载自blog.csdn.net/HdUIprince/article/details/82932207