Given a the head to a singly linked list complete the method

Given a the head to a singly linked list, complete the method to find the kth to last element in the list. class Node {int data; Node next;} public Node kthToLast(int k, Node head) {//complete the implementation

Solution

//Returns the kth last node from the last
public Node kthToLast(int k,Node head)
{
//Initialise first and second object to head
Node first = head,second = head;
  
//move second object to k steps from the head
while(k!=0)
{
//If second becomes null then k is larger than the length of the linked list
//So return null
if(second==null)
return null;
  
//Move second one step forward
second = second.next;
  
//Decrease the value of k
k--;
}
  
//Now till second reaches the end of the linked list
//Move first and second one step forward together.
//After this loop first will point to the kth node from last.
while(second.next!=null)
{
second = second.next;
first = first.next;
}
  
return first;
}

 Given a the head to a singly linked list, complete the method to find the kth to last element in the list. class Node {int data; Node next;} public Node kthToL

Get Help Now

Submit a Take Down Notice

Tutor
Tutor: Dr Jack
Most rated tutor on our site