在堆栈中搜索

时间:2014-03-21 10:35:03

标签: c search stack

这是我搜索部分的代码,但它不起作用。你能给我一些帮助吗?我是编程的新手,我真的很喜欢指针。感谢。

typedef struct Dictionary_Entry{
    int index;
    char character[100];
    struct Dictionary_Entry *link;
}Dictionary_Entry;

typedef struct Dictionary{
    Dictionary_Entry *top;
}Dictionary;

int check_in_dictionary(Dictionary *dictionary, char string[100], char file_char[100]){
    Dictionary_Entry *runner = dictionary->top;
    strcat(string, file_char);
        while(runner != NULL){
            if((strcmp(string, runner->character)) == 0){
                break;
                return runner->index;
            }
        }
        return -1;
}

3 个答案:

答案 0 :(得分:2)

break关键字离开循环,因此您的return runner->index行不会被执行。交换两行(或删除break,因为return 离开循环,然后你应该没问题。

答案 1 :(得分:1)

以下是我的评论以////

开头的更正版本
int check_in_dictionary(Dictionary *dictionary, char string[100], char file_char[100]){
    Dictionary_Entry *runner = dictionary->top;
    strcat(string, file_char);
    while(runner != NULL){
      if((strcmp(string, runner->character)) == 0){
         return runner->index;  // found
         //// break not neccessary here as return returns anyway
      }
      runner = runner->link ;  //// goto next entry
    }
    return -1;
}

BTW strcat(string, file_char);不是必需的,您可以直接与file_char进行比较strcmp(file_char, runner->character)

答案 2 :(得分:0)

您需要在while循环中扫描Dictionary。 像这样的东西:

 while(runner != NULL){
        if((strcmp(string, runner->character)) == 0){
            return runner->index;
        }
    runner = runner->next; /* go to next element in dictionary */
    }