Why there is segmentation fault ?
Kth element from the last in linked list
@Shashank-Shekhar-2351214838461151 hey ,what logic you have applied I think this is not logic for this problem. Two pointer concept will be used here,Maintain two pointers – reference pointer and main pointer. Initialize both reference and main pointers to head. First, move reference pointer to n nodes from head. Now move both pointers one by one until the reference pointer reaches the end. Now the main pointer will point to nth node from the end. Return the main pointer.
I have done the same, here my temp is reference pointer and temp1 is main pointer, I moved the temp to k position and then moved temp and temp1 simultaneously until end is reached through temp.
@Shashank-Shekhar-2351214838461151 bro apne merge ka code bhej dia hai,pls check the code link above.
Arey, I have only used the name merge but the code is of the kth element from the last, so please don’t get confused.
@Shashank-Shekhar-2351214838461151 hey apko extra cases me consider krne honge when you are traversing upto k nodes may be that can happen if nodes are less than k,see this code for implemntation:
void printNthFromLast( struct Node *head, int n)
{
struct Node *main_ptr = head;
struct Node *ref_ptr = head;
int count = 0;
if (head != NULL)
{
while ( count < n )
{
if (ref_ptr == NULL)
{
printf ( "%d is greater than the no. of "
"nodes in list" , n);
return ;
}
ref_ptr = ref_ptr->next;
count++;
} /* End of while*/
while (ref_ptr != NULL)
{
main_ptr = main_ptr->next;
ref_ptr = ref_ptr->next;
}
printf ( "Node no. %d from last is %d " ,
n, main_ptr->data);
}
}
I hope I’ve cleared your doubt. I ask you to please rate your experience here
Your feedback is very important. It helps us improve our platform and hence provide you
the learning experience you deserve.
On the off chance, you still have some questions or not find the answers satisfactory, you may reopen
the doubt.