数据结构:单向链表系列4--获取链表长度(迭代法和递归法)

获取链表长度(迭代法和递归法)

迭代法

1、设定一个计数器,初始值为0

2、初始化current到头节点

3、如果current不为null进行以下循环

     a) current = current -> next
     b) count++;

4、返回计数器

c语言:
/* Counts no. of nodes in linked list */
int getCount(struct Node* head) 
{ 
    int count = 0;  // Initialize count 
    struct Node* current = head;  // Initialize current 
    while (current != NULL) 
    { 
        count++; 
        current = current->next; 
    } 
    return count; 
} 

java:

 /* Returns count of nodes in linked list */
    public int getCount() 
    { 
        Node temp = head; 
        int count = 0; 
        while (temp != null) 
        { 
            count++; 
            temp = temp.next; 
        } 
        return count; 
    } 

c#:

 /* Returns count of nodes in linked list */
    public int getCount() 
    { 
        Node temp = head; 
        int count = 0; 
        while (temp != null) 
        { 
            count++; 
            temp = temp.next; 
        } 
        return count; 
    } 

 递归法

int getCount(head)
1) If head is NULL, return 0.
2) Else return 1 + getCount(head->next) 
c语言:
/* Counts the no. of occurrences of a node 
   (search_for) in a linked list (head)*/
int getCount(struct Node* head) 
{ 
    // Base case 
    if (head == NULL) 
        return 0; 
  
    // count is 1 + count of remaining list 
    return 1 + getCount(head->next); 
}

java

  /* Returns count of nodes in linked list */
    public int getCountRec(Node node) 
    { 
        // Base case 
        if (node == null) 
            return 0; 
  
        // Count is this node plus rest of the list 
        return 1 + getCountRec(node.next); 
    }

c#

 /* Returns count of nodes in linked list */
    public int getCountRec(Node node)  
    {  
        // Base case  
        if (node == null)  
            return 0;  
  
        // Count is this node plus rest of the list  
        return 1 + getCountRec(node.next);  
    }  

 文章来源:https://www.geeksforgeeks.org/find-length-of-a-linked-list-iterative-and-recursive/

原文地址:https://www.cnblogs.com/passedbylove/p/11439236.html