Skip to content

Latest commit

 

History

History
24 lines (20 loc) · 719 Bytes

File metadata and controls

24 lines (20 loc) · 719 Bytes

package com.thealgorithms.linkedlist;

public class FindMiddleNode {

public static ListNode findMiddle(ListNode head) {
    ListNode slow = head, fast = head;
    while (fast != null && fast.next != null) {
        slow = slow.next;
        fast = fast.next.next;
    }
    return slow; // middle node
}

public static void main(String[] args) {
    ListNode head = new ListNode(1);
    head.next = new ListNode(2);
    head.next.next = new ListNode(3);
    head.next.next.next = new ListNode(4);
    head.next.next.next.next = new ListNode(5);

    ListNode middle = findMiddle(head);
    System.out.println("Middle node value: " + middle.val);
}

}