Length of Linked List in Java | Data Structure and Algorithm


Blog Content
  • Linked List size calculation by making our own class and function.
  • Linked List size calculation by using an inbuilt java library(easy one).
In this blog, we will learn how to make a program to calculate the length of the linked list in Java. We will make this by using two methods in one we define our custom function and make it and in another, we will use an inbuilt java library to calculate the size of the linked list




Method 1

//we have to define first class of our LinkedList

class LinkedList<T>{
    T data;
    LinkedList<T> next;
    LinkedList(T data){
        this.data = data;
    }
}
public class Main
{
//this function will calculate the length of the linked list
    public static int lenghtLL(LinkedList<Integer> head){
        int count=0;
        while(head!=null){
            count++;
            head= head.next;
        }
        return count;
        
    }
public static void main(String[] args) {
//defining linkedlist variable name , data type (Integer in our case) and data
LinkedList<Integer> a = new LinkedList<>(10);
LinkedList<Integer> b = new LinkedList<>(20);
LinkedList<Integer> c = new LinkedList<>(30);
LinkedList<Integer> d = new LinkedList<>(40);

//defining the relation a.next means a contains that data value of it own and //address of the b data
a.next =b;
b.next=c;
c.next =d;
    System.out.println(lenghtLL(a));
}
}

 

Method 2

In this, we will use an inbuilt library of java to get the size of the linked list

import java.util.LinkedList;

public class Main

{

public static void main(String[] args) {

    LinkedList<Integer> a = new LinkedList<>();

    a.add(10);

    a.add(20);

    a.add(30);

    a.add(40);

    a.add(50);

System.out.println(a.size());

}

}



Next : Print the ith Node in Linked List Java

Post a Comment

0 Comments