Search This Blog

Sunday, September 21, 2014

WAP to find nth node from the last in a singly linked list

list_t *nth_node_from_last(int pos_from_last)
{
    int len_of_ll = 0;
    list_t *temp = NULL;
    for(len_of_ll = 0,temp = start;temp;temp=temp->next,len_of_ll++);
    // Length of LL is obtained
    len_of_ll -= pos_from_last;
    if ( len_of_ll <= 0)
    {
        printf("Position from last is out side the linked list range");
        return NULL;
    }
    for(temp = start;len_of_ll;temp=temp->next,len_of_ll--);
    return temp;
}

No comments:

Post a Comment