Cute Angel
Cute Angel

Reputation: 31

nth data from tail of a single linked list

I don't know why my approach does not work for the given problem.

Here is the code:

void last_to_n(struct node*head,int n)
{
    struct node *temp = head;
    struct node *temp2 = head;
    int len1=0,len2=0;
    while(temp!=NULL)
    {
        len1++;
        temp=temp->next;
    }
    while(temp2!=NULL)
    {
        if(len2==len1-n+1)printf("%d",temp2->data);
        else
        {
            len2++;
            temp2=temp2->next;
        }
    }

}

Is anything wrong with the code?

Upvotes: 2

Views: 35

Answers (2)

sat
sat

Reputation: 336

  1. You should put break in 2nd while loop, otherwise it won't terminate and will lead to a crash.
  2. if(len2==len1-n+1) condition is wrong. It should be if(len2==len1-n).

Upvotes: 5

StuartLC
StuartLC

Reputation: 107357

As per @sat, you should terminate once you have found your element, otherwise the while loop will never exit as the next-node navigation is wrapped in the else, and the if condition will continue to be true as len2 isn't incremented.

Assuming the 0th last element is the tail element:

struct node *temp = head;
struct node *temp2 = head;
int len1 = 0, len2 = 0;

// Count nodes
while (temp != NULL) {
    len1++;
    temp = temp->next;
}

if (n >= len1)
    return;

while (temp2 != NULL) {
    if (len2 == len1 - n - 1) {
        printf("%d", temp2->data);
        break;
    }
    len2++;
    temp2 = temp2->next;
}

Upvotes: 1

Related Questions