Regarding finding the middle element of linked list

后端 未结 5 1625
轮回少年
轮回少年 2021-02-04 20:19

I am following the below approach to calculate the middle element from the linked list , but I want is there any built in method or any other approach which can als

5条回答
  •  花落未央
    2021-02-04 20:58

    public Node getMiddleElement(Node head) {
        Node slow_pointer=head;
        Node fast_pointer=head;
        while(fast_pointer.next!=null && fast_pointer.next.next!=null)
        {
            slow_pointer=slow_pointer.next;
            fast_pointer=fast_pointer.next.next;
        }
        return slow_pointer;
    }
    
    Node mid_elem=PrintMiddleElement(head);
    System.out.println(mid_elem.data);
    

    I/P:5 10 15 25 35 25 40 O/P:25

提交回复
热议问题