简体   繁体   English

如何在递归中找到C中元素的索引

[英]how to find index of element in C with recursion

i have this, it checks if element is in list or not, but how get the index of element ? 我有这个,它检查元素是否在列表中,但如何获取元素的索引?

// function that check if element is in list
int checklist(struct list *my_list, int n) {
  while (my_list != NULL) {
    if(my_list->info == n) return 1;
    my_list = my_list->next;
  }
  return 0;
}

Use additional variable to remember the current index: 使用其他变量来记住当前索引:

int checklist (struct list *my_list,int n) {
int i=0;
while (my_list != NULL) {
 if(my_list->info == n) return i;
 my_list = my_list->next;
 i++;
 }
return -1; 
}

or 要么

int checklist (struct list *my_list,int n) {
int i;
for (i=0;my_list != NULL; i++, my_list = my_list->next) 
 if(my_list->info == n) return i;
return -1; 
}

By the way your code has nothing to do with recursion, i think its called linked list. 顺便说一句,你的代码与递归无关,我认为它叫做链表。

Use an additional argument to the function which carries the index you're currently looking at. 对包含您当前正在查看的索引的函数使用附加参数。 Though you need a way to return it: return -1 if the list is exhausted and the index of the first found item otherwise. 虽然你需要一种方法来返回它:如果列表用尽则返回-1,否则返回第一个找到的项的索引。

PS I don't see any recursion here. PS我在这里看不到任何递归。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM