首页 > 解决方案 > 在 C 中的链表中搜索

问题描述

我正在编写一个函数来搜索c中链表中的元素,如果元素存在,它会起作用,但我不知道如何编写代码,以便在元素不存在时返回“未找到”。这是搜索功能

void search(Node *head, int c)
{ 
    int count = 0;
    Node *temp3 = head;

    while (temp3 != NULL) {
        if (temp3->data != c) {
            count++;
            temp3 = temp3->next;
            printf("Element found at: %d \n", count);
        } else 
            printf("Element not found");
    } 
}

标签: clinked-list

解决方案


您应该只遍历列表并设置一个标志或在找到元素时计算出现次数(除了打印其节点号)。然后,如果是这种情况,您可以测试要打印的标志"Element not found"

void search(Node *head, int c) { 
    int count = 0, found = 0;

    for (Node *temp3 = head; temp3 != NULL; temp3 = temp3->next) {
        count++;
        if (temp3->data == c) {
            found++;
            printf("Element found at: %d\n", count);
        }
    }
    if (!found) {
        printf("Element not found\n");
    } 
}

推荐阅读