Home > Enterprise >  How to correctly print a message if a match is found in a linked list?
How to correctly print a message if a match is found in a linked list?

Time:11-25

I'm creating a method that finds the element I want in a linked list and return its index: it should either return index or unsuccessful message, However, my program prints both:

The code:

void findVal(int val, myNode *head) {
  myNode *p = NULL;
  p = head;
  int i = 0;
  while (p != NULL){
      if (val == p->val){
        printf("\nthe id is:%d.",i);
        }
      p = p->next;
      i  ;
    }
  printf("cannot find the value");
}

The result (I want to find all the '4' in a linked list, "123456478"):

the id is 3
the id is 6
cannot find the value

I then used return; this printed the first 4's id then stopped looping. The thing is I have two '4' in my linked list: 123456478.

if (val == p->val){
    printf("\nthe id is:%d.",i);
    return;
}

Then I thought about using an array to store the index every time a match is found. And after the loop, if the array is empty, then print unsuccessful message, however if the array is not empty, then prints all the indexes.

However, I believe there is a much better solution, so could anyone please help?

CodePudding user response:

You just need a 'flag' variable, set to zero initially and then set it to non-zero if/when you find a match. If, after the loop has finished, that flag is still zero, then show the "not found" message:

void findVal(int val, myNode *head) {
    int found = 0;
    myNode *p = head;
    int i = 0;
    while (p != NULL){
        if (val == p->val){
            printf("\nthe id is:%d.\n",i);
            found = 1; // Set the flag to non-zero.
        }
        p = p->next;
        i  ;
    }
    if (found == 0) {
        printf("cannot find the value\n");
    }
}
  • Related