【问题标题】:I'm having trouble creating a function to search for a string in my linked list我在创建一个函数来搜索我的链接列表中的字符串时遇到问题
【发布时间】:2020-12-11 14:38:20
【问题描述】:

我一直在做一个项目,我正在为它搞清楚后勤工作,所以我在将它们实施到实际程序之前先制作基本功能。我一直在构建一个大链表,其中包含从名为 words.txt 的 txt 文件中读取的一组单词。在阅读了这些单词并将它们放入链接列表之后,我一直在尝试让一些功能正常工作,但我做不到。第一个是从链表中搜索一个字符串,并在打印列表的其余部分后打印它。 (我不需要为我的程序打印单词我只需要找到它,但现在,我正在打印它来测试功能。)第二个是从链接列表中删除我搜索的单词.在源代码中,我只包含了尝试搜索单词的代码,因为我完全删除了删除功能,因为我想从头开始。

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

/*Node of linked list*/
typedef struct node {
    char *data;
    struct node *next;
} node;

node *start = NULL;
node *current;

/*Void function to print list*/
void printList(struct node *node)
{
    while (node != NULL) {
        printf("%s ", node->data);
        node = node->next;
    }
}

/*Appending nodes to linked list*/
void add(char *line) {
    node *temp = malloc(sizeof(node));
    temp->data = strdup(line);
    temp->next = NULL;
    current = start;

    if(start == NULL) {
        start = temp;
    } else {
        while(current->next != NULL) {
            current = current->next;
        }
        current->next = temp;
    }
}

void readfile(char *filename) {
    FILE *file = fopen(filename, "r");

    if(file == NULL) {
        exit(1);
    }
    char buffer[512];
    while(fgets(buffer, sizeof(buffer), file) != NULL) {
        add(buffer);
    }
    fclose(file);
}

node *listSearch(node* start, char nodeSearched){
    node *p;
    for (p = start; p != NULL; p = p->next)
        if (strcmp(p->data, nodeSearched) == 0)
            printf("%s", p);
    return NULL;
}

int main(){
    readfile("words.txt");
    printList(start);
    listSearch(start, "word");
    return 0;
}

Link to the txt file in case you need it

【问题讨论】:

  • node *listSearch(node* start, char nodeSearched){ 不应该是:node *listSearch(node* start, char* nodeSearched){ 吗?第二个参数应该是char*而不是char,不是吗?
  • 我这样做了,但还是不行
  • 我不是在告诉你该怎么做,我是在要求澄清。我想你在将代码复制到问题时可能犯了一个错误。

标签: c singly-linked-list


【解决方案1】:

您的代码是正确的,但几乎没有错误。您节点中的字符串最后还包含\n。尝试在 readfile 函数中处理它,或者您可以搜索 word\n 而不是 word,这将为您提供正确的答案。并使用char* nodeSearched

【讨论】:

  • 非常感谢!
【解决方案2】:

以下建议的代码:

  1. 干净编译
  2. 包含适当的错误检查
  3. 执行所需的功能
  4. 包含//cleanup cmets,你需要通过free()将每个分配的内存区域实际返回到堆中,否则如果发生错误,代码会泄漏内存
  5. 请注意该结构与该结构的 typedef 的分离,以提高灵活性。
  6. 注意使用 #define 语句来避免“神奇”数字
  7. 请注意从每个单词输入中删除了尾随 \n
  8. 注意将global 变量移动到main() 函数的内部,并将参数从main() 函数适当地传递到子函数
  9. 注意链表第一个条目的特殊处理
  10. 注意在 cmets //debug 之后对 printf() 的调用,以便于区分作为程序功能一部分的对 printf() 的调用和对用于调试的 printf() 的调用
  11. 注意对宏名称和typedef 名称使用大写
  12. 请注意,我使用了您提供的输入文件
  13. 请注意,在 C 中,可以在不引用 NULL 的情况下测试 NULL 字符串。这极大地有助于“整理”代码
  14. 使用仅大小写不同的变量和结构名称(fileFILE)是一种糟糕的编程习惯。所以将file 替换为fp(`文件描述符指针的典型简写)
  15. 请注意使用适当的水平和垂直间距以方便我们人类阅读

现在,建议的代码。

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define MAX_BUF_LEN  512
#define MAX_WORD_LEN 20


/*Node of linked list*/
struct node 
{
    char data[ MAX_WORD_LEN ];
    struct node *next;
};

typedef struct node NODE;


/*Void function to print list*/
void printList( NODE *head)
{
    NODE *current = head;
    
    while ( current ) 
    {
        printf("list value: %s\n", current->data);
        current = current->next;
    }
}


/*Appending nodes to linked list*/
void addNode( NODE **head, char *line ) 
{
    
    NODE *temp = malloc(sizeof( NODE ));
    if ( ! temp )
    {
        perror( "malloc failed" );
        //todo: cleanup
        exit( EXIT_FAILURE );
    }
    
    // implied else, malloc successful
    
    strcpy( temp->data, line );
    temp->next = NULL;
    
    NODE *current = *head;

    if( ! current ) 
    { // then, first node
        //debug
        //printf( "%s\n", "adding first node" );
        *head = temp;
    } 
    
    else 
    {
        while( current->next ) 
        {
            current = current->next;
        }
        
        //debug
        //printf( "%s\n", "appending new node" );
        current->next = temp;
    }
}


void readfile( NODE **head, char *filename) 
{
    FILE *fp = fopen(filename, "r");

    if( ! fp ) 
    { 
        perror( "fopen failed" );
        exit( EXIT_FAILURE );
    }
    
    // implied else, fopen successful
    
    char buffer[ MAX_BUF_LEN ];
    while( fgets( buffer, sizeof(buffer), fp ) ) 
    {
        // remove (possible) trailing newline
        buffer [ strcspn( buffer, "\n" ) ] = '\0';
        
        //debug
        //printf( "result of fgets: %s\n", buffer );
        
        addNode( head, buffer );
    }
    fclose(fp);
}


NODE *listSearch( NODE *head, char *dataToFind )
{
    NODE *current = NULL;
    
    for ( current = head; current; current = current->next )
    {
        //debug
        //printf( "searching found: %s\n", current->data );
        if (strcmp( current->data, dataToFind ) == 0)
        {
            printf( "%s\n", current->data );
            break;
        }
    }
    return current;
}


int main( void )
{
    NODE *head = NULL;

    readfile( &head, "words.txt");
    printList( head );
    char searchWord[] = "word";
    
    NODE *foundNode = listSearch( head, searchWord );
    if( ! foundNode )
    {
        printf( "search for >%s< failed\n", searchWord );
    }
    
    else
    {
        printf( "search for: >%s< successful\n", searchWord );
    }
    
    // cleanup
    for( NODE *current = head; current; current = current->next )
    {
        free( current );
    }
    
    return 0;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-06-11
    • 1970-01-01
    • 1970-01-01
    • 2021-12-10
    • 2021-01-10
    • 1970-01-01
    • 2013-05-31
    相关资源
    最近更新 更多