/*
 * Copyright (C) 2014 Pedro Vicente Gómez Sánchez.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.github.pedrovgs.problem64;

/**
 * Given a singly linked list, can you write a method to return the element in the middle of the
 * list?
 *
 * @author Pedro Vicente Gómez Sánchez.
 */
public class GetTheElementInTheMiddleOfTheList {

}

@@ -645,16 +645,65 @@
 lem64;%0A%0A
+import com.github.pedrovgs.linkedlist.ListNode;%0A%0A
 /**%0A * G
@@ -901,10 +901,1196 @@
 List %7B%0A%0A
+  /**%0A   * Iterative solution to this problem. The complexity order of this algorithm in time terms is%0A   * equals to O(N) where N is the number of elements in the list. In space terms, the complexity%0A   * order is O(1) because we are not using any auxiliary data structure to solve this problem.%0A   * This algorithm is based on know the size of the list, but this part of the algorithm is a%0A   * problem for the execution time.%0A   */%0A  public ListNode%3CInteger%3E get(ListNode%3CInteger%3E list) %7B%0A    validateInput(list);%0A%0A    int size = getListSize(list);%0A    int middleElementPosition = size %25 2 != 0 ? size / 2 : (size / 2) - 1;%0A    ListNode middleElement = list;%0A    for (int i = 0; i %3C middleElementPosition; i++) %7B%0A      middleElement = middleElement.getNext();%0A    %7D%0A    return middleElement;%0A  %7D%0A%0A  private int getListSize(ListNode%3CInteger%3E list) %7B%0A    int size = 0;%0A    ListNode currentNode = list;%0A    while (currentNode != null) %7B%0A      size++;%0A      currentNode = currentNode.getNext();%0A    %7D%0A    return size;%0A  %7D%0A%0A  private void validateInput(ListNode list) %7B%0A    if (list == null) %7B%0A      throw new IllegalArgumentException(%22You can't pass a null instance of list%22);%0A    %7D%0A  %7D%0A
 %7D%0A

Add solution to problem 64