top of page
Search
Writer's pictureAbhinaw Tripathi

Write an algorithm to find the k'th to last element of a singly linked list.


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.

3 views0 comments

Recent Posts

See All
bottom of page