Find the middle of a given linked list

Given a singly linked list, find middle of the linked list.

 For example, if given linked list is 1->2->3->4->5 then output should be 3.

If there are even nodes, then there would be two middle nodes, we need to print second middle element. For example, if given linked list is 1->2->3->4->5->6 then output should be 4.

Code:

package microsoftInterviewPrep;

public class MiddleOfList {
   
    Node head;
   
    class Node{
       
        int data;
        Node next;
       
        Node(int data){
            this.data = data;
            next = null;
        }
    }
   
   
    static void  printMiddle(Node head){
       
        Node slow = head;
        Node fast = head;
       
        while(fast != null && fast.next != null){
            slow = slow.next;
            fast = fast.next.next;
        }
       
        System.out.println("Middle element is: "+ slow.data);
       
       
    }
   
    void push(int data){
       
        Node node = new Node(data);
        node.next = head;
        head = node;
       
       
    }
   
   
    public static void main(String[] args){
       
        MiddleOfList llist = new MiddleOfList();
       
            for (int i=5; i>0; --i)
            {
                llist.push(i);
                printMiddle(llist.head);
            }
       
       
    }

}


Output:

Middle element is: 5
Middle element is: 5
Middle element is: 4
Middle element is: 4
Middle element is: 3


Comments

Popular posts from this blog

Rearrange Array in Maximum-Minimum form

Second Largest Element

Check if a number is a power of another number