Linked List: Find the middle of the linked list

Question: Find the middle of a linked list. For example, if the given linked list is 1->2->3->4->5 then the output should be 3. 
If there are even nodes, then there would be two middle nodes, we need to print the second middle element. For example, if the given linked list is 1->2->3->4->5->6 then the output should be 4. 
Throw an exception if the list is empty.

 //method to get the middle of the linked list
    public int getMiddle() throws Exception {

        //throw an exception if list is null
        if (head == null) {
            throw new Exception("List is Empty");
        } else {
            //find the length of the linked list
            int length = findLength();

            //index: to keep a count of the number of nodes traversed
            //middle: indicates the middle node number
            int index = 0, middle = length / 2;

            //temp: pointer which traverses the linked list
            ListNode temp = head;
            
            //traverse till the middle node
            while (index != middle) {
                temp = temp.getNext();
                index++;
            }
            //return the value of the middle node
            return temp.getData();
        }
    }

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