Given a linked list and an integer N, you need to find and return index where N is present in the Linked List. Return -1 if n is not present in the Linked List.
Indexing of nodes starts from 0.
Input format:
Line 1: Linked list elements (separated by space and terminated by -1)
Line 2: Integer n
Output format:
Index
Example:
Sample Input 1:
3 4 5 2 6 1 9 -1
5
Sample Output 1:
2
Sample Input 2:
3 4 5 2 6 1 9 -1
6
Sample Output 2:
4
In this question, we define a temp pointer and equating it with head of the Linked List. We have to keep an integer index keeping the track of the temp node. We keep on traversing while temp != NULL. On each traversal, we check whether temp's data and the user's data. If they are equal, we return the index. Else we increment index by 1 and temp to temp-> next.
At last if we don’t find the element, we return -1.
Algorithm:
Function:
//Function for finding the node int findNodeInLL(Node* head, int data){ //Used to keep track of the Node Index int index = 0; Node * temp = head; //LinkedList traversal for finding the node while(temp!=NULL){ if(temp->data == data){ //If element found return index return index; } temp = temp->next; index++; } //If element not found return -1; }C++ code
Output
need an explanation for this answer? contact us directly to get an explanation for this answer