Write a Program to get Nth node in a Linked List

Write a Program to get Nth node in a Linked List:-

1. Initialize count = 1
2. Traverse Linked List through Loop:-
     a. Run Loop Until count is  Not equal to the Nth number.When count=n Terminate Loop and                  return Current Node or print That current node->data
     b. Increment count
     c. change current to current->next.

#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;

}

void count(struct node *head,int n)
{
struct node *current;
current=head;
int count=1;

while(count!=n)
{
current=current->next;
count++;
}
if(count=n)
{
printf("%dth node is:%d\n",n,current->data);
}

}

void LinkListTraversal(struct node *n)

{
while(n->next!=0)
{
printf("%d\t",n->data);
n=n->next;
}
printf("\n");
}

main()
{

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

insert(&head,1);
insert(&head,2);
insert(&head,3);
insert(&head,4);

int n;
printf("Find nth node:\n");
scanf("%d",&n);

count(head,n);

LinkListTraversal(head);

}


Copyright © C Program | Java | OpenGL Programming | Hadoop at Computaholics