Reputation: 31
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
Reputation: 336
if(len2==len1-n+1)
condition is wrong. It should be if(len2==len1-n)
.Upvotes: 5
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