I am getting run error in first test case
import java.util.*;
public class Main {
public static void main(String args[]) {
// Your Code Here
Scanner scan = new Scanner(System.in);
LinkedList l = new LinkedList();
while(true){
int n = scan.nextInt();
if(n!=-1){
l.addLast(n);
}
else{
break;
}
}
int k = scan.nextInt();
System.out.println(l.nodeAtKLast(k));
}
}
class LinkedList{
private class Node{
int data;
Node next;
}
private Node head; // To hold the address of the first node
private Node tail; // To hold the address of the Last Node
private int size; // no. of nodes
// functions
public void addFirst(int item) // to add the node at First Position
{
Node nn = new Node(); // creating new Node [item | address of next Node]
nn.data = item;
nn.next = null;
if(size ==0) // this is my first node so my head is the address of this node as well as the tail
{
this.head = nn; //nn hold the address of my node
this.tail = nn;
this.size++;
}else // i already have first node [] head->[]-[]-[]-[]-[]
{ nn.next = this.head; // so my new node will hold the address of my first node
this.head = nn; // my head will shift to the new added node
this.size++;
}
}
public void addLast(int item){
// creating the node
Node nn = new Node();
nn.data = item;
nn.next= null;
//Attaching node
if(size==0){
this.head = nn;
this.tail = nn;
this.size++;
}else{
// Now my last node will become 2nd LASt so my tail.next will hold the address of my newly added node
this.tail.next = nn;
this.tail = nn;
this.size++;
}
}
public int nodeAtKLast(int k){
Node temp = this.head;
Node temp2 = this.head;
while(k>0 ){
//System.out.println("*");
temp = temp.next;
k--;
}
while(temp.next!=null){
temp2 = temp2.next;
temp = temp.next;
}
return temp2.next.data;
}
}