Find middle element of LinkedList [closed]

Posted on

Problem

    private static String findMiddleElementOfLinkedList(Node head) {
        if (head == null) {
            return null;
        }
        Node slowCursor = head;
        if (slowCursor.next != null) {
            Node fastCursor = head.next.next;
            while (fastCursor != null) {
                slowCursor = slowCursor.next;
                fastCursor = fastCursor.next.next;
            }
        }

        return String.valueOf(slowCursor.data);
    }
}

Solution

fastCursor = fastCursor.next.next; will crash if the number of nodes in the list is even (but greater than zero).

Leave a Reply

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