c - 在 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");
}
}
解决方案
您应该只遍历列表并设置一个标志或在找到元素时计算出现次数(除了打印其节点号)。然后,如果是这种情况,您可以测试要打印的标志"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");
}
}
推荐阅读
- git - 当我选中“阻止命令行推送”复选框时,为什么我不能推送?
- azure - 将域的子文件夹映射到 azure app servive
- javascript - 如何使用 lodash 在 javascript 中实现多级排序?
- android - 如何在加载应用程序时存储未来数据以供进一步使用?# 颤动
- assembly - 如何堆叠(推送)xPSR?
- javascript - js中的定时动作(每秒帧数)
- bash - 将文件作为输入并在其上运行 awk 命令
- go - 如何在go中保存和加载接口结构
- python - 使用 MetPy 生成 Countour 图的问题
- c++ - 我将如何添加或乘以极大的数字,例如 20 位数字 x 5 位数字......?