Home coding Write a program to find node at given index in linkedlist.

Write a program to find node at given index in linkedlist.

0
84

Given a linkedlist,we have to find the node at given index in linkedlist and print the resultant node.

Example:

Input:1 2 3 4 5 6  k=2;
Output:2

Logic:

STEP 1:Traverse a linkedlist,until we reach the end of linkedlist.
STEP 2:maintain a count variable while iterating the linkedlist.
STEP 3:when we reached at end then print that node .

Code

int findLinkedlist(Node *head,int k)
{
    if(head==NULL)
    {
        return 0;
    }
    int index=0;
    while(head!=NULL &&index<k)
    {
        head=head->next;
        index++;
    }
   return head->index; 
    
}

Ouput:

1 2 3 4 5 6
k= 3
output:

3

Time Complexity:O(N)

Space Complexity:O(1)

NO COMMENTS

LEAVE A REPLY

Please enter your comment!
Please enter your name here