Linked List: Find the length of the linked list

Question: Write a function that returns the length of the linked list. Throw an exception if the list is empty.

public class LinkedList {
    //data fields
    //head node
    ListNode head;

    //constructor to initialize head node
    public LinkedList(){
        head=null;
    }
  
  //method to find the length of the linked list
    public int findLength() throws Exception{
        //set the length to zero initially
        int linkedListLength=0;

        //throw exception if the list is empty
        if(head==null){
            throw new Exception("List is Empty");
        } else {
            //start from the head of the linked list
            ListNode temp=head;
            //traverse the linked list till the last node i.e when temp reaches null
            while(temp!=null){
                linkedListLength++;
                temp= temp.getNext();
            }
        }
        return linkedListLength;
    }
}

Leave a Reply

PHP JS HTML CSS BASH PYTHON CODE

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this:
search previous next tag category expand menu location phone mail time cart zoom edit close