The Gateway to Computer Science Excellence

0 votes

int find (struct node * first, int n) { while (first data ! = n) first = first — next; if (first data = = n) return(1); else return (-1);

in the above code segment if the value of 'n' is 5, then the function return 1, but if the value of 'n' is 9, then what does it do ?

+1

This is the code.

#include<stdio.h> #include<stdlib.h> struct Node { int data; struct Node *next; }; int find (struct Node* first, int n) { while (first->data != n) first = first->next; if (first->data == n) return(1); else return (-1); } void push(struct Node **head_ref, int data) { struct Node *ptr1 = (struct Node *)malloc(sizeof(struct Node)); struct Node *temp = *head_ref; ptr1->data = data; ptr1->next = *head_ref; if (*head_ref != NULL) { while (temp->next != *head_ref) temp = temp->next; temp->next = ptr1; } else ptr1->next = ptr1; *head_ref = ptr1; } void printList(struct Node *head) { struct Node *temp = head; if (head != NULL) { do { printf("%d ", temp->data); temp = temp->next; } while (temp != head); } } int main() { struct Node *head = NULL; push(&head, 3); push(&head, 5); push(&head, 12); push(&head, 18); printf ("%d ", find(head, 9)); return 0; }

Check this out.

+1

from the image, we have to understand that it is a circular linked list.

So, Due to circular linked list and given code, if you are searching a element which is not present in the list, then it will lead to **INFINITE LOOP**

0

It is not cased that it always will go in infinite loop.it also depend on the implementation of the algorithm.But here it will go in the infinite loop.

52,315 questions

60,436 answers

201,775 comments

95,252 users