recent

C Program to Find Nth node from the end of a Linked List

Nth node from the end of a Linked List:-

1) Calculate the length of Linked List. Let the length be 'n'.
2) Print the( (n+1)-Nth)th node from the begining of the Linked List.
>
#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 n,int Nth)
{
struct node *current;
current=head;
int x=1;
while(x!=(n+1)-Nth)
{
current=current->next;
x++;
}

printf("%d\n",current->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,n,Nth);

}
Powered by Blogger.