Find Length of a Linked List (Iterative and Recursive) - GeeksforGeeks

20 Jan, 2022
Write a function to count the number of nodes in a given singly linked list. 
For example, the function should return 5 for linked list 1->3->1->2->1. 
Iterative Solution 
1) Initialize count as 0 
2) Initialize a node pointer, current = head.
3) Do following while current is not NULL
     a) current = current -> next
     b) count++;
4) Return count 
Following are the Iterative implementations of the above algorithm to find the count of nodes in a given singly linked list. 
C++
C
Java
Python3
C#
Javascript
// Iterative C++ program to find length// or count of nodes in a linked list#include <bits/stdc++.h>using namespace std; /* Link list node */class Node{    public:    int data;    Node* next;}; /* Given a reference (pointer to pointer) to the headof a list and an int, push a new node on the frontof the list. */void push(Node** head_ref, int new_data){    /* allocate node */    Node* new_node =new Node();     /* put in the data */    new_node->data = new_data;     /* link the old list off the new node */    new_node->next = (*head_ref);     /* move the head to point to the new node */    (*head_ref) = new_node;} /* Counts no. of nodes in linked list */int getCount(Node* head){    int count = 0; // Initialize count    Node* current = head; // Initialize current    while (current != NULL)    {        count++;        current = current->next;    }    return count;} /* Driver program to test count function*/int main(){    /* Start with the empty list */    Node* head = NULL;     /* Use push() to construct below list    1->2->1->3->1 */    push(&head, 1);    push(&head, 3);    push(&head, 1);    push(&head, 2);    push(&head, 1);     /* Check the count function */    cout<<"count of nodes is "<< getCount(head);    return 0;} // This is code is contributed by rathbhupendra
// Iterative C program to find length or count of nodes in a linked list#include<stdio.h>#include<stdlib.h> /* Link list node */struct Node{    int data;    struct Node* next;}; /* Given a reference (pointer to pointer) to the head  of a list and an int, push a new node on the front  of the list. */void push(struct Node** head_ref, int new_data){    /* allocate node */    struct Node* new_node =            (struct Node*) malloc(sizeof(struct Node));     /* put in the data  */    new_node->data  = new_data;     /* link the old list off the new node */    new_node->next = (*head_ref);     /* move the head to point to the new node */    (*head_ref)    = new_node;} /* 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;} /* Driver program to test count function*/int main(){    /* Start with the empty list */    struct Node* head = NULL;     /* Use push() to construct below list     1->2->1->3->1  */    push(&head, 1);    push(&head, 3);    push(&head, 1);    push(&head, 2);    push(&head, 1);     /* Check the count function */    printf("count of nodes is %d", getCount(head));    return 0;}
// Java program to count number of nodes in a linked list /* Linked list Node*/class Node{    int data;    Node next;    Node(int d)  { data = d;  next = null; }} // Linked List classclass LinkedList{    Node head;  // head of list     /* Inserts a new Node at front of the list. */    public void push(int new_data)    {        /* 1 & 2: Allocate the Node &                  Put in the data*/        Node new_node = new Node(new_data);         /* 3. Make next of new Node as head */        new_node.next = head;         /* 4. Move the head to point to new Node */        head = new_node;    }     /* 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;    }     /* Driver program to test above functions. Ideally       this function should be in a separate user class.       It is kept here to keep code compact */    public static void main(String[] args)    {        /* Start with the empty list */        LinkedList llist = new LinkedList();        llist.push(1);        llist.push(3);        llist.push(1);        llist.push(2);        llist.push(1);         System.out.println("Count of nodes is " +                           llist.getCount());    }}
# A complete working Python program to find length of a# Linked List iteratively # Node classclass Node:    # Function to initialise the node object    def __init__(self, data):        self.data = data # Assign data        self.next = None # Initialize next as null  # Linked List class contains a Node objectclass LinkedList:     # Function to initialize head    def __init__(self):        self.head = None      # This function is in LinkedList class. It inserts    # a new node at the beginning of Linked List.    def push(self, new_data):         # 1 & 2: Allocate the Node &        #     Put in the data        new_node = Node(new_data)         # 3. Make next of new Node as head        new_node.next = self.head         # 4. Move the head to point to new Node        self.head = new_node      # This function counts number of nodes in Linked List    # iteratively, given 'node' as starting node.    def getCount(self):        temp = self.head # Initialise temp        count = 0 # Initialise count         # Loop while end of linked list is not reached        while (temp):            count += 1            temp = temp.next        return count  # Code execution starts hereif __name__=='__main__':    llist = LinkedList()    llist.push(1)    llist.push(3)    llist.push(1)    llist.push(2)    llist.push(1)    print ("Count of nodes is :",llist.getCount())
// C# program to count number// of nodes in a linked listusing System;     /* Linked list Node*/public class Node{    public int data;    public Node next;    public Node(int d)    {        data = d; next = null;    }} // Linked List classpublic class LinkedList{    Node head; // head of list     /* Inserts a new Node at front of the list. */    public void push(int new_data)    {        /* 1 & 2: Allocate the Node &                Put in the data*/        Node new_node = new Node(new_data);         /* 3. Make next of new Node as head */        new_node.next = head;         /* 4. Move the head to point to new Node */        head = new_node;    }     /* 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;    }     /* Driver program to test above functions. Ideally    this function should be in a separate user class.    It is kept here to keep code compact */    public static void Main()    {        /* Start with the empty list */        LinkedList llist = new LinkedList();        llist.push(1);        llist.push(3);        llist.push(1);        llist.push(2);        llist.push(1);         Console.WriteLine("Count of nodes is " +                        llist.getCount());    }} /* This code contributed by PrinciRaj1992 */
<script>// javascript program to count number of nodes in a linked list /* Linked list Node*/class Node {    constructor(val) {        this.data = val;        this.next = null;    }} // Linked List classvar head; // head of list     /* Inserts a new Node at front of the list. */     function push(new_data) {        /*         * 1 & 2: Allocate the Node & Put in the data         */        var new_node = new Node(new_data);         /* 3. Make next of new Node as head */        new_node.next = head;         /* 4. Move the head to point to new Node */        head = new_node;    }     /* Returns count of nodes in linked list */     function getCount() {        var temp = head;        var count = 0;        while (temp != null) {            count++;            temp = temp.next;        }        return count;    }     /*     * Driver program to test above functions. Ideally this function should be in a     * separate user class. It is kept here to keep code compact     */             /* Start with the empty list */        push(1);        push(3);        push(1);        push(2);        push(1);         document.write("Count of nodes is " + getCount()); // This code contributed by Rajput-Ji</script>
Output: 
count of nodes is 5
Recursive Solution 
int getCount(head)
1) If head is NULL, return 0.
2) Else return 1 + getCount(head->next) 
Following are the Recursive implementations of the above algorithm to find the count of nodes in a given singly linked list. 
C++
Java
Python3
C#
Javascript
// Recursive C++ program to find length// or count of nodes in a linked list#include <bits/stdc++.h>using namespace std; /* Link list node */class Node {public:    int data;    Node* next;}; /* Given a reference (pointer to pointer) to the headof a list and an int, push a new node on the frontof the list. */void push(Node** head_ref, int new_data){    /* allocate node */    Node* new_node = new Node();     /* put in the data */    new_node->data = new_data;     /* link the old list off the new node */    new_node->next = (*head_ref);     /* move the head to point to the new node */    (*head_ref) = new_node;} /* Recursively count number of nodes in linked list */int getCount(Node* head){    // Base Case    if (head == NULL) {        return 0;    }    // Count this node plus the rest of the list    else {        return 1 + getCount(head->next);    }} /* Driver program to test count function*/int main(){    /* Start with the empty list */    Node* head = NULL;     /* Use push() to construct below list    1->2->1->3->1 */    push(&head, 1);    push(&head, 3);    push(&head, 1);    push(&head, 2);    push(&head, 1);     /* Check the count function */    cout << "Count of nodes is " << getCount(head);    return 0;} // This is code is contributed by rajsanghavi9
// Recursive Java program to count number of nodes in// a linked list /* Linked list Node*/class Node{    int data;    Node next;    Node(int d)  { data = d;  next = null; }} // Linked List classclass LinkedList{    Node head;  // head of list     /* Inserts a new Node at front of the list. */    public void push(int new_data)    {        /* 1 & 2: Allocate the Node &                  Put in the data*/        Node new_node = new Node(new_data);         /* 3. Make next of new Node as head */        new_node.next = head;         /* 4. Move the head to point to new Node */        head = new_node;    }     /* 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);    }     /* Wrapper over getCountRec() */    public int getCount()    {        return getCountRec(head);    }     /* Driver program to test above functions. Ideally       this function should be in a separate user class.       It is kept here to keep code compact */    public static void main(String[] args)    {        /* Start with the empty list */        LinkedList llist = new LinkedList();        llist.push(1);        llist.push(3);        llist.push(1);        llist.push(2);        llist.push(1);         System.out.println("Count of nodes is " +                           llist.getCount());    }}
# A complete working Python program to find length of a# Linked List recursively # Node classclass Node:    # Function to initialise the node object    def __init__(self, data):        self.data = data  # Assign data        self.next = None  # Initialize next as null  # Linked List class contains a Node objectclass LinkedList:     # Function to initialize head    def __init__(self):        self.head = None      # This function is in LinkedList class. It inserts    # a new node at the beginning of Linked List.    def push(self, new_data):         # 1 & 2: Allocate the Node &        #        Put in the data        new_node = Node(new_data)         # 3. Make next of new Node as head        new_node.next = self.head         # 4. Move the head to point to new Node        self.head = new_node     # This function counts number of nodes in Linked List    # recursively, given 'node' as starting node.    def getCountRec(self, node):        if (not node): # Base case            return 0        else:            return 1 + self.getCountRec(node.next)     # A wrapper over getCountRec()    def getCount(self):       return self.getCountRec(self.head) # Code execution starts hereif __name__=='__main__':    llist = LinkedList()    llist.push(1)    llist.push(3)    llist.push(1)    llist.push(2)    llist.push(1)    print ('Count of nodes is :',llist.getCount())
// Recursive C# program to count number of nodes in// a linked listusing System;  /* Linked list Node*/public class Node{    public int data;    public Node next;    public Node(int d)    {        data = d; next = null;    }} // Linked List classpublic class LinkedList{    Node head; // head of list     /* Inserts a new Node at front of the list. */    public void push(int new_data)    {        /* 1 & 2: Allocate the Node &                Put in the data*/        Node new_node = new Node(new_data);         /* 3. Make next of new Node as head */        new_node.next = head;         /* 4. Move the head to point to new Node */        head = new_node;    }     /* 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);    }     /* Wrapper over getCountRec() */    public int getCount()    {        return getCountRec(head);    }     /* Driver program to test above functions. Ideally    this function should be in a separate user class.    It is kept here to keep code compact */    public static void Main(String[] args)    {        /* Start with the empty list */        LinkedList llist = new LinkedList();        llist.push(1);        llist.push(3);        llist.push(1);        llist.push(2);        llist.push(1);         Console.WriteLine("Count of nodes is " +                        llist.getCount());    }} // This code is contributed 29AjayKumar
<script>// Recursive javascript program to count number of nodes in// a linked list /* Linked list Node*/class Node {    constructor(val) {            this.data = val;            this.next = null;        }    }     // Linked List class    var head; // head of list     /* Inserts a new Node at front of the list. */    function push( new_data) {        /*         * 1 & 2: Allocate the Node & Put in the data         */        var new_node = new Node(new_data);         /* 3. Make next of new Node as head */        new_node.next = head;         /* 4. Move the head to point to new Node */        head = new_node;    }     /* Returns count of nodes in linked list */     function getCountRec(node) {        // Base case        if (node == null)            return 0;         // Count is this node plus rest of the list        return 1 + getCountRec(node.next);    }     /* Wrapper over getCountRec() */     function getCount() {        return getCountRec(head);    }     /*     * Driver program to test above functions. Ideally this function should be in a     * separate user class. It is kept here to keep code compact     */             /* Start with the empty list */             push(1);        push(3);        push(1);        push(2);        push(1);         document.write("Count of nodes is " + getCount()); // This code contributed by gauravrajput1</script>
Output: 
Count of nodes is 5
 
YouTubeGeeksforGeeks507K subscribersFind Length of a Linked List (Iterative and Recursive) | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.More videosMore videosYou're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 10:23•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=kX_OJsOcK8Q" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>
This article is contributed by Ravi. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above 
29AjayKumar
princiraj1992
rathbhupendra
Akanksha_Rai
Rajput-Ji
GauravRajput1
rajsanghavi9
simranarora5sos
amartyaghoshgfg
Linked List
Linked List
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Implementing a Linked List in Java using Class
Circular Linked List | Set 1 (Introduction and Applications)
Merge Sort for Linked Lists
Remove duplicates from a sorted linked list
Detect and Remove Loop in a Linked List
Function to check if a singly linked list is palindrome
Top 20 Linked List Interview Question
Remove duplicates from an unsorted linked list
Reverse a Linked List in groups of given size | Set 1
Write a function to get the intersection point of two Linked Lists