用C语言在链表中搜索

用C语言在链表中搜索,c,linked-list,C,Linked List,我正在编写一个函数来搜索c中链表中的一个元素,如果该元素存在,它可以工作,但我不知道如何编写代码,以便在该元素不存在时返回“not found”。 这里是搜索功能 void search(Node *head, int c) { int count = 0; Node *temp3 = head; while (temp3 != NULL) { if (temp3->data != c) { count++;

我正在编写一个函数来搜索c中链表中的一个元素,如果该元素存在,它可以工作,但我不知道如何编写代码,以便在该元素不存在时返回“not found”。 这里是搜索功能

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");
    } 
}

如果列表只能包含元素的一次出现,那么返回它可能会更有帮助:

Node*搜索(Node*head,int c)
{
节点*n;
对于(n=head;n!=NULL;n=n->next){
如果(n->data==c)
打破
}
返回n;
}
//其他地方
Node*res=搜索(head,123);
如果(res!=NULL){
//做点什么
}否则{
放置(“未找到元素”);
}

可能的解决方案如下(-1被解释为未找到):


您应该在列表中循环,并在找到元素时设置一个标志或计数出现次数(除了打印其节点号)。然后,如果出现这种情况,您只需测试标记以打印
“未找到元素”

void搜索(节点*head,int c){
int count=0,found=0;
对于(节点*temp3=head;temp3!=NULL;temp3=temp3->next){
计数++;
如果(temp3->data==c){
发现++;
printf(“元素位于:%d\n”,计数);
}
}
如果(!找到){
printf(“未找到元素\n”);
} 
}

不清楚该函数将返回什么。请进一步解释当1时您希望程序执行什么操作。元素被找到,并且2。当找不到元素时。您希望函数在打印适当的消息后继续运行,还是在打印消息后在这两种情况下都返回?如果您希望函数在打印适当的消息后继续运行,它是否应该在两种情况下运行相同的代码?正如旁注:在第二个示例中,您可以简单地为(n=head;n!=NULL&&n->data!=c;n=n->next)编写
//空语句
这样,
如果(n->data==c)中断不是必需的。@AndreasWenzel我为什么要这样做?它在语义上是等价的,只是更难理解。就个人而言,我认为我的版本更容易理解,因为循环将一直运行到
n==NULL
n->data==c
。因此,我认为在
while
语句中使用
&&
运算符组合这两个循环条件是有意义的,而不是在
while
块中使用
break
语句。然而,我想这是一个品味的问题。不管怎样,我还是对你的答案投了赞成票。@AndreasWenzel空for循环从来都不容易理解IMHO,特别是对于新手程序员来说。我想这是品味的问题\_(ツ)_/''请添加对您的示例的简要说明一旦找到元素,继续搜索似乎效率低下。但是,OP没有明确说明所需元素是否可以多次出现在列表中(至少有一个其他答案假设情况并非如此),因此我也对该答案进行了投票。
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);
            break;
        } 
    } 
    if(temp3 == NULL)
            printf("Element not found");

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

    while(temp3 != NULL )
    {
        if(temp3 -> data == c) {
            return count;
        } else(temp3 -> data != c) {
            ++count;
            temp3 = temp3 -> next;
        } 
    } 
    return -1;
}