Find Nth element in a linked list

Hello readers,

This post is on finding the Nth node in a linked list.
Linked list plays an important role when it comes to data storing and accessing data.
Searching / traversing a linked list has a time complexity of O(1) which is way better than any other data structure.
Check out the implementation given below.

Source Code:


/*create a node that has a data and link to the next node*/
struct node{

int data;
struct node* next;
/*Function 1 :Inserting nodes to a linked list in a sorted order */
void insert(struct node** head, struct node* newnode)
struct node* run;
/* case 1: Inserting first node , Check if head is NULL
case 2: The node to be inserted is lesser than the head node*/
if (*head == NULL || (*head)->data >= newnode->data)
newnode->next = *head;
*head = newnode;
/*Inserting nodes in their right positions, by traversing the linked list */

run = *head;

while (run->next!=NULL && run->next->data < newnode->data)
run = run->next;
newnode->next = run->next;
run->next = newnode;
struct node* newNode(int data)
struct node* new_node=(struct node*)malloc(sizeof(struct node));
return new_node;

/* Function to find the Nth element in the linked list
Passing the linked list and nth value to the function*/
int find_Nth_node(struct node* head, int n)
struct node* run = head;
int count = 0;
/*run pointer traverses the linked list
with the count variable initialized to zero*/
while (run != NULL)
/*when the count matches with n function returns the current node’s data*/
if (count == n)
run = run->next;

/*function returns -1 when there is no such node as nth node*/
return -1;

int main()
/*creating a linked list and add values to it*/
struct node* head = NULL;
int value;
insert(&head, newNode(6));
insert(&head, newNode(7));
insert(&head, newNode(2));
insert(&head, newNode(22));
insert(&head, newNode(13));
/*call the function*/
value=find_Nth_node(head, 4);
printf(“Value at n 4 is %d”, value);
printf(“Value doesnt exist”);

[/source code]

Latest posts by abirami vijayakumar (see all)

Leave a Reply

Your email address will not be published. Required fields are marked *