logo CodeStepByStep logo

kthFromLast

Related Links:

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
    ...
}
Partial class: Write code that will become part of an existing class as described. You do not need to write the complete class, just the portion described in the exercise.

You must log in before you can solve this problem.

Log In

Need help?

Stuck on an exercise? Contact your TA or instructor.

If something seems wrong with our site, please

Is there a problem? Contact us.