Return Nth the node from the end of the linked list.
Time Complexity is O(n).
#include<stdio.h>
#define null 0
typedef struct list
{
int n;
struct list *next;
}node;
node *findmthnode(node *s,int m)
{
int i;
node *h1=s,*h2=s;
for(i=1;i<=m;i++)
{
if(h1==null)
return null;
h1=h1->next;
}
while(h1)
{
h1=h1->next;
h2=h2->next;
}
return h2;
}
main()
{
node *h=null,*new1=null,*prev,*t;
char ch;
int k,m;
do
{
printf("\n Enter the number to inseret into list ");
scanf("%d",&k);
new1=(node *)malloc(sizeof(node));
new1->n=k;
new1->next=null;
if(h==null)
{
h=new1;
prev=new1;
}
else
{
prev->next=new1;
prev=new1;
}
getchar();
printf("\n Press Y or y if U Want to continue enter the no's ");
scanf("%c",&ch);
}while(ch=='y' || ch=='Y');
printf("\n List Is ");
t=h;
while(t!=null)
{
printf(" %d",t->n);
t=t->next;
}
do
{
printf("\n Enter value of m (not 0) to find the mth node from end of the list");
scanf("%d",&m);
if(m!=0)
{
t=findmthnode(h,m);
if(t==null)
{
printf("\n m is greater than the total no of nodes");
}
else
{
printf("Value Of Node %d from the end of list is %d",m,t->n);
}
}
}while(m!=0);
}
We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.