Skip to content

Find Length of a Linked List data structure (Iterative and Recursive)

  • by

How to Find Length of Linked List data structure?

Linked list

A linked list is a linear data structure where each element is a separate object. Counting a node in a linked list is important in programming when we are using a linked list data structure. It will help you solve many problems like fining nth node from last. So do good programming practice it can your next interview question.

Linked list in java interview

Method 1.  Iterative : The Iteration is applied to the set of instructions which we want to get repeatedly executed.

package in.eyehunt.data.struc;

// Linked list Node.
class Node {
    int data;
    Node next;
    // Parameterized constructor
    Node(int d) {
        data = d;
        next = null;
    }
}
public class LinkedList {

    Node head; // head of list
    //Returns count of nodes in linked list (iteration)
    public int count() {
        int a = 0;
        Node n = head;
        while (n != null) {
            n = n.next;
            a++;
        }
        return a;
    }
    public static void main(String a[]) {
        //create a simple linked list with 3 nodes
        LinkedList linkedList = new LinkedList();
        linkedList.head = new Node(2);
        Node second = new Node(4);
        Node third = new Node(5);
        linkedList.head.next = second;
        second.next = third;

        System.out.print("Total nodes in LikedList is : " + linkedList.count());
    }
}

Output : Total nodes in LikedList is : 3

Method 2.  Recursive : Recursion is a process, where statement in a body of function calls the function itself.

package in.eyehunt.data.struc;

// Linked list Node.
class Node {
    int data;
    Node next;
    // Parameterized constructor
    Node(int d) {
        data = d;
        next = null;
    }
}
public class LinkedList {

    Node head; // head of list

    //Returns count of nodes in linked list (Recursion)
    public int countRecursive(Node node) {
        if (node == null ){
            return 0;
        }
        return 1 + countRecursive(node.next);
    }
    public static void main(String a[]) {

        //create a simple linked list with 3 nodes
        LinkedList linkedList = new LinkedList();
        linkedList.head = new Node(2);
        Node second = new Node(4);
        Node third = new Node(5);
        Node fourth = new Node(9);
        linkedList.head.next = second;
        second.next = third;
        third.next = fourth;

        System.out.print("Total nodes in LikedList is : " + linkedList.countRecursive(linkedList.head));

    }
}

Output : Total nodes in LikedList is : 4

Find Length of a Linked List data structure is relate top question in a list of. Based on this Find Length of Linked List, you can solve many Linked List questions.

Leave a Reply

Your email address will not be published. Required fields are marked *