We can approach this problem in two ways one using recursive way and other using non recursive way.if you will use recursive way then its complexity will be o(n) where n=number of elements in the linked-list.
Solution 1: if the linked list size is known then the problem is very easy such as
let say the size if the size is known then kth to last element is the (length - k)th element .
Solution 2:
public static int nthToLast(LinkedListNode head,int k)
{
if(head == null)
return 0;
int i=nthToLast(head.next,k)+ 1;
for(i==k)
{
System.out.println(head.data);
}
return i;
}
Since it is recursive solution then it takes o(n) space due to recursive calls.
Solution 1: if the linked list size is known then the problem is very easy such as
let say the size if the size is known then kth to last element is the (length - k)th element .
Solution 2:
public static int nthToLast(LinkedListNode head,int k)
{
if(head == null)
return 0;
int i=nthToLast(head.next,k)+ 1;
for(i==k)
{
System.out.println(head.data);
}
return i;
}
Since it is recursive solution then it takes o(n) space due to recursive calls.
No comments:
Post a Comment