zoukankan      html  css  js  c++  java
  • 466. Count Linked List Nodes【Naive】

    Count how many nodes in a linked list.

    Example

    Given 1->3->5, return 3.

    解法一:

     1 /**
     2  * Definition of ListNode
     3  * class ListNode {
     4  * public:
     5  *     int val;
     6  *     ListNode *next;
     7  *     ListNode(int val) {
     8  *         this->val = val;
     9  *         this->next = NULL;
    10  *     }
    11  * }
    12  */
    13 
    14 
    15 class Solution {
    16 public:
    17     /*
    18      * @param head: the first node of linked list.
    19      * @return: An integer
    20      */
    21     int countNodes(ListNode * head) {
    22         if (head == NULL) {
    23             return 0;
    24         } else if (head->next == NULL) {
    25             return 1;
    26         }
    27         
    28         return 1 + countNodes(head->next);
    29     }
    30 };

    递归

    解法二:

     1 /**
     2  * Definition of ListNode
     3  * class ListNode {
     4  * public:
     5  *     int val;
     6  *     ListNode *next;
     7  *     ListNode(int val) {
     8  *         this->val = val;
     9  *         this->next = NULL;
    10  *     }
    11  * }
    12  */
    13 
    14 
    15 class Solution {
    16 public:
    17     /*
    18      * @param head: the first node of linked list.
    19      * @return: An integer
    20      */
    21     int countNodes(ListNode * head) {
    22         if (head == NULL) {
    23             return 0;
    24         } 
    25         
    26         int sum = 0;
    27         while (head != NULL) {
    28             ++sum;
    29             head = head->next;
    30         }
    31         
    32         return sum;
    33     }
    34 };
  • 相关阅读:
    ESP8266简单几步建立服务器
    SVM推导
    标准的最大margin问题
    switch用法
    vecor预分配内存溢出2
    vector预分配空间溢出
    [面试编程题]算法基础-字符移位
    [面试编程题1]构造回文
    一天学完UFLDL
    神经网络中的XOR问题
  • 原文地址:https://www.cnblogs.com/abc-begin/p/8409612.html
Copyright © 2011-2022 走看看