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 };