Question: Given a MyLinkedList class , the task is to implement a method to find the n'th Node from the end of the list. int getNthFromLast(MyLinkedList
Given a MyLinkedList class, the task is to implement a method to find the n'th Node from the end of the list.
int getNthFromLast(MyLinkedList list, int n)
The method getNthFromLast, takes two arguments, the MyLinkedList list and an integer n.
You're ONLY allowed to use the provided methods in the given MyLinkedList class.
Input: Every test case contains two lines.
First line of a test case contains data items of linked list.
Second line of a test case contains value of n.
Output:
Output a single integer that is the nth integer in the linked list from the end.
Print -1 if the value of n is zero or greater than the number of elements in the linked list.
Sample Example:
In the first example, there are 9 nodes in linked list and we need to find 2nd node from end. 2nd node from end is 8.
Input1: 1 2 3 4 5 6 7 8 9 2
Output1: 8 -----------------------------------
In the second example, there are 4 nodes in linked list and we need to find 5th from end. Since 'n' is more than number of nodes in linked list, output is -1.
Input2: 1 2 3 4 5
Output2: -1
-------------------------------------
In the third example, there are 6 nodes in linked list and we need to find 0th from end. Since 'n' is zero, output is -1.
Input3: 1 2 3 4 5 6 0
Output3: -1
********Solution****************
import java.util.Arrays; import java.util.Scanner;
public class Solution{
/* * My Solution */ public static int getNthFromLast(MyLinkedList list, int n){ //Write your code here
} //DO NOT CHANGE ---------------------------------- public static void main(String[] args) { Scanner input = new Scanner(System.in); String str = input.nextLine(); int n = input.nextInt(); input.close(); int[] arr = Arrays.stream(str.substring(0, str.length()).split("\\s")) .map(String::trim).mapToInt(Integer::parseInt).toArray(); MyLinkedList list = new MyLinkedList(); for(int i = 0; i < arr.length; i++){ list.addLast(arr[i]); } System.out.println(Solution.getNthFromLast(list, n)); } //DO NOT CHANGE ----------------------------------
}
Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
