top button
Flag Notify
    Connect to us
      Site Registration

Site Registration

How to find 3rd element from end in a linked list in one pass?

+3 votes
624 views
How to find 3rd element from end in a linked list in one pass?
posted Aug 7, 2015 by Mohammed Hussain

Share this question
Facebook Share Button Twitter Share Button LinkedIn Share Button

1 Answer

0 votes
/* Function to get the nth node from the last of a linked list*/
void printNthFromLast(struct node* head, int n)
{
    int len = 0, i;
    struct node *temp = head;

    // 1) count the number of nodes in Linked List
    while (temp != NULL)
    {
        temp = temp->next;
        len++;
    }

    // check if value of n is not more than length of the linked list
    if (len < n)
      return;

    temp = head;

    // 2) get the (n-len+1)th node from the begining
    for (i = 1; i < len-n+1; i++)
       temp = temp->next;

    printf ("%d", temp->data);

    return;
}
answer Aug 7, 2015 by Amit Kumar Pandey
...