FindKthElement { public ListNode find(ListNode listNode, int k) { validateInput(listNode, k); ListNode reversedList = reverseLinkedList.reverseIterative(listNode); ListNode result = reversedList; while (k > 0) { result = result.getNext(); if (result == null) { throw new IndexOutOfBoundsException(); } k--; } return result; } FindKthElement(); ListNode find(ListNode listNode, int k); ListNode find2(ListNode listNode, int k); ListNode find3(ListNode listNode, int k);  }
@Test(expected = IllegalArgumentException.class) public void shouldNotAcceptNullListNodes() { findElement.find(null, 4); }
@Test(expected = IllegalArgumentException.class) public void shouldNotAcceptNegativePositions() { findElement.find(new ListNode<Integer>(3), -1); }
@Test(expected = IndexOutOfBoundsException.class) public void shouldNotAcceptPositionsGreaterThanListSize() { findElement.find(new ListNode<Integer>(3), 2); }
@Test public void shouldReturnLastNodeIfPositionIsZero() { ListNode result = findElement.find(new ListNode<Integer>(1), 0); ListNode<Integer> expectedNode = new ListNode<Integer>(1); assertEquals(expectedNode, result); }
@Test public void shouldReturnFirstElementIfPositionIsEqualsToListSizeMinusOne() { ListNode<Integer> list = createList(new int[] { 1, 2, 3 }); ListNode result = findElement.find(list, 2); ListNode<Integer> expectedNode = new ListNode<Integer>(1); assertEquals(expectedNode, result); }
@Test public void shouldReturnKthToLastElement() { ListNode<Integer> list = createList(new int[] { 1, 2, 3 }); ListNode result = findElement.find(list, 1); ListNode<Integer> expectedNode = new ListNode<Integer>(2); assertEquals(expectedNode, result); }