Friday, April 19, 2019

Find k-th node from end in Linked List



void print_kth_from_end(Node *head, int k){
    Node *lead = head;
    Node *lag = head;
    while(k > 0){
        if(lead){
            k--;
            lead = lead->next;
        }
        else{
            std::cout << "K is larger than length of Linked List" << std::endl;
            return;
        }
    }
    while(lead){
        lead = lead->next;
        lag = lag->next;
    }
    std::cout << "kth node from end = " << lag->data << std::endl;
}


Detailed explanation can be found on Youtube:


Subscribe to KnowledgeCenter

No comments:

Post a Comment

LeetCode 30 Day Challenge | Day 7 | Counting Elements

Given an integer array  arr , count element  x  such that  x + 1  is also in  arr . If there're duplicates in  arr , count them sepe...