GetTheElementInTheMiddleOfTheList { public ListNode<Integer> get(ListNode<Integer> list) { validateInput(list); int size = getListSize(list); int middleElementPosition = size % 2 != 0 ? size / 2 : (size / 2) - 1; ListNode middleElement = list; for (int i = 0; i < middleElementPosition; i++) { middleElement = middleElement.getNext(); } return middleElement; }  ListNode<Integer> get(ListNode<Integer> list); ListNode<Integer> get2(ListNode<Integer> list);  }
@Test(expected = IllegalArgumentException.class) public void shouldNotAcceptNullListInstances() { getTheElementInTheMiddleOfTheList.get(null); }
@Test public void shouldReturnTheElementInTheMiddleOfAListWithAnEvenNumberOfElements() { ListNode<Integer> list = createList(new int[] { 1, 2, 3 }); ListNode<Integer> middleElement = getTheElementInTheMiddleOfTheList.get(list); assertEquals(Integer.valueOf(2), middleElement.getData()); }
@Test public void shouldReturnTheElementInTheMiddleOfTheListWithAnOddNumberOfElements() { ListNode<Integer> list = createList(new int[] { 1, 2, 3, 4 }); ListNode<Integer> middleElement = getTheElementInTheMiddleOfTheList.get(list); assertEquals(Integer.valueOf(2), middleElement.getData()); }