FindKthElement { public ListNode find2(ListNode listNode, int k) { validateInput(listNode, k); int size = calculateListSize(listNode); if (k > (size - 1)) { throw new IndexOutOfBoundsException(); } ListNode result = listNode; int n = size - 1 - k; while (n > 0) { result = result.getNext(); n--; } 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 shouldNotAcceptNullListNodes2() { findElement.find2(null, 4); }
@Test(expected = IllegalArgumentException.class) public void shouldNotAcceptNegativePositions2() { findElement.find2(new ListNode<Integer>(3), -1); }
@Test(expected = IndexOutOfBoundsException.class) public void shouldNotAcceptPositionsGreaterThanListSize2() { findElement.find2(new ListNode<Integer>(3), 2); }
@Test public void shouldReturnLastNodeIfPositionIsZero2() { ListNode result = findElement.find2(new ListNode<Integer>(1), 0); ListNode<Integer> expectedNode = new ListNode<Integer>(1); assertEquals(expectedNode, result); }
@Test public void shouldReturnFirstElementIfPositionIsEqualsToListSizeMinusOne2() { ListNode<Integer> list = createList(new int[] { 1, 2, 3 }); ListNode result = findElement.find2(list, 2); ListNode<Integer> expectedNode = new ListNode<Integer>(1); assertEquals(expectedNode, result); }
@Test public void shouldReturnKthToLastElement2() { ListNode<Integer> list = createList(new int[] { 1, 2, 3 }); ListNode result = findElement.find2(list, 1); ListNode<Integer> expectedNode = new ListNode<Integer>(2); assertEquals(expectedNode, result); }