Web Toolbar by Wibiya

Pages

Tuesday, April 19, 2011

In a linked list, find the nth element from the end.

Solution #1: An intuitive approach would be to do this problem recursively. Recursively travel till the last node and then get back till we reach the nth node from the end. Here is the code,

void nthElementRec(node* lptr, int n)
{
    static int index = 1;

    if(lptr->next == NULL)
        return;

    nthElementRec(lptr->next, n);
    index++;

    if(index == n)
        printf("%d\n", lptr->data);
}


Solution #2: Take two pointers, p1 and p2, and make them point to first and nth element from the beginning respectively. Now increment both the pointers till p2 reaches the end. At this point p1 will point to the nth element from the end. Here is the code,

void nthElement(node* lptr, int n)
{
    node* p1;
    node* p2;
    int i;

    p1 = p2 = lptr;

    for(i=0; i<n-1; i++)
        p2=p2->next;

    while(p2->next != NULL)
    {
        p1 = p1->next;
        p2 = p2->next;
    }

    printf("%d\n", p1->data);
}


No comments: