Posts Kth from End of Linked List (geeksforgeeks - SDE Sheet)
Post
Cancel

Kth from End of Linked List (geeksforgeeks - SDE Sheet)

PROBLEM DESCRIPTION

Given the head of a linked list and the number k, Your task is to find the kth node from the end. If k is more than the number of nodes, then the output should be -1.

geeksforgeeks

SOLUTION

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
class Solution {

    int getKthFromLast(Node head, int k) {

        Node f = head;

        int count = k;

        while(count > 0){

            // this can happen is k is more than the number of nodes
            if(f == null)
                return -1;

            f = f.next;
            count--;

        }

        Node s = head;

        while(f != null){
            s = s.next;
            f = f.next;
        }

        return s.data;

    }
}
This post is licensed under CC BY 4.0 by the author.