Write a method kthFromLast
that accepts an integer k as a parameter and returns the kth from last element from a linked list.
For example, if a variable list
contains the following values:
[9, 4, 7, -1, 18, 2, 0, 6]
The call of list.kthFromLast(3)
would return 2
.
The call of list.kthFromLast(5)
would return -1
.
If k is not positive or the list does not have k or more elements, throw a NoSuchElementException
.
Do not modify the linked list.
Do not create any auxiliary collections.
Assume that you are adding this method to the LinkedIntList
class as defined below:
public class LinkedIntList {
private ListNode front; // null for an empty list
...
}