recent

C Program to Find Nth node from the end of a Linked List(Recursive Method)

Find Nth node from the end of a Linked List(Recursive Method):-

1. i==Nth
2.print that Node

#include<stdio.h>
#include<stdlib.h>

struct node{

int data;
struct node *next;
};

void insert(struct node **head,int new_data)
{
struct node *new_node;
new_node=(struct node*)malloc(sizeof(struct node));

new_node->data=new_data;
new_node->next=*head;
*head=new_node;

}

int count(struct node *head)
{
int count=0;
struct node *current;
current=head;
while(current->next!=0)
{
current=current->next;
count++;
}
return count;
}

int TraverseFromLast(struct node *head,int Nth)
{
   int i = 0;
    if(head == NULL)
       return;
   TraverseFromLast(head->next, Nth);
    if(++i == Nth)
       printf("%d\n", head->data);
}
main()
{

struct node *head;
head=(struct node*)malloc(sizeof(struct node));

insert(&head,1);
insert(&head,2);
insert(&head,3);
insert(&head,4);
insert(&head,5);
insert(&head,6);
insert(&head,7);
insert(&head,8);
insert(&head,9);
insert(&head,10);


int n=count(head);
int Nth;

printf("Nth element from last\n");
scanf("%d",&Nth);

TraverseFromLast(head,Nth);

}
Powered by Blogger.