2012-12-06 39 views
1

我有這個,它檢查元素是否在列表中,但如何獲得元素的索引?如何找到C中的元素的索引與遞歸

// 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; 
} 
+0

這是代碼,我誤另一個 – unknown

+0

INT清單(結構列表* my_list,INT N) { 而海報{ 如果(my_list->信息== n)的返回1(my_list!= NULL); my_list = my_list-> next; } return 0; } – unknown

+4

請修改您的問題以代替正確的代碼。 – dutt

回答

1

對攜帶您正在查看的索引的函數使用附加參數。儘管您需要一種方法來返回它:如果列表已用盡,則返回-1,否則返回第一個找到的項目的索引。

P.S.我在這裏沒有看到任何遞歸。

2

使用額外的變量記住當前指數:

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

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

通過你的代碼無關遞歸的方式,我認爲其所謂的鏈接列表。

+0

非常感謝:) – unknown

+0

沒問題,只要標記其中的一個答案,如果其足夠的其他社區成員會看到這個問題已經解決。 – Kyborek