如何将链表和函数指针作为输入

how to take a linked list and a function pointer as inputs

我是 C 的新手,正在尝试学习函数 pointer.I 我应该完成“map_list”函数,该函数采用链表和函数指针,return 一个新列表以相同的顺序排列,但具有所有值 squared.Please 指出我做错的地方。

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


struct Link {
    struct Link *next;
    int value;
};

void print_list(struct Link *list) {
    for(struct Link *l = list; l != NULL; l = l->next) {
        printf("%d", l->value);

        if(l->next) {
            printf(", ");
        }
    }

    printf("\n");
}


struct Link *append(int x, struct Link *head) {
    struct Link *head_ = (struct Link*)malloc(sizeof(struct Link));
    head_->next = head;
    head_->value = x;

    return head_;
}

struct Link *reverse_list(struct Link *list) {
    struct Link *head = NULL;

    for(struct Link *l = list; l != NULL;) {
        struct Link *next = l->next;
        l->next = head;
        head = l;

        l = next;
    }

    return head;
}

struct Link *map_list(struct Link *link_list,int (*Square)(int)   ) {

    struct Link *new_list = NULL;
    new_list = new_list ->next;
    new_list ->value = (*Square)(link_list ->value);
    return new_list;
}

int square(int x) {
    return x * x;
}

int add3(int x) {
    return x + 3;
}



struct Link *theList() {
    struct Link *l = append(1, NULL);
    l = append(2, l);
    l = append(3, l);
    l = append(5, l);
    return l;
}

int main() {


    struct Link *l = theList();
    print_list(map_list(l, &square));
    ;
    return 0;
}

我得到了'Segmentation fault (core dumped)'

如果我没理解错的话,您在编写函数 map_list 时遇到了一些问题。 它可以看起来像下面这样

struct Link * map_list( const struct Link *link_list, int operation( int )   ) 
{
    struct Link *new_list  = NULL;
    struct Link **new_node = &new_list;

    for ( const struct Link *current = link_list; current != NULL; current = current->next )
    {
        *new_node = malloc( sizeof( struct Link ) );

        ( *new_node )->next  = NULL;
        ( *new_node )->value = operation( current->value );

        new_node = &( *new_node )->next;
    } 

    return new_list;
}

并且函数可以被调用,例如

map_list( l, square );

map_list( l, add3 );

该函数不检查节点的内存分配是否成功。您可以自己添加这样的检查。

至于你自己的功能实现

struct Link *map_list(struct Link *link_list,int (*Square)(int)   ) {

    struct Link *new_list = NULL;
    new_list = new_list ->next;
    new_list ->value = (*Square)(link_list ->value);
    return new_list;
}

然后对于初学者来说它有未定义的行为

ew_list = new_list ->next;

相对于作业没有意义。