链表中返回struct node指针:函数返回类型与返回语句问询
链表查找函数的返回类型与返回语句修正
1. 正确的返回类型
你需要让position函数返回struct node类型的指针,因此函数的返回类型必须从int改为struct node *,函数声明应写为:
struct node *position(int key)
2. 正确的返回语句
原返回语句return struct node *p1;是错误的,C语言中返回指针时直接返回指针变量即可,修正后的返回语句为:
return p1;
额外的代码修正建议
除了返回类型和返回语句,原代码还有两处明显问题需要修正:
position函数中多余的malloc:这个函数的职责是查找节点,不需要创建新节点,直接删除struct node *new=(struct node*)malloc(sizeof(struct node));这一行insertafter函数调用position时缺少参数:必须传入要查找的key值,比如p1 = position(目标key);,同时需要处理未找到节点的情况(返回NULL时)
修正后的完整代码示例
// 先确保链表节点结构已定义 struct node { int info; struct node *link; }; struct node *head; // 全局头指针,需根据实际场景初始化 // 修正后的position函数:查找对应key的节点并返回指针 struct node *position(int key) { struct node *p1 = head; // 先判断p1不为空,避免空指针访问 while (p1 != NULL && p1->info != key) { p1 = p1->link; } // 找到则返回节点指针,未找到返回NULL return p1; } // 修正后的insertafter函数:在指定key的节点后插入新节点 void insertafter(int target_key, int new_data) { struct node *target_node = position(target_key); // 未找到目标节点时直接返回 if (target_node == NULL) { return; } // 创建新节点并赋值 struct node *new_node = (struct node*)malloc(sizeof(struct node)); new_node->info = new_data; // 完成插入操作 new_node->link = target_node->link; target_node->link = new_node; }
内容的提问来源于stack exchange,提问作者Risher322
相关产品推荐
相关产品推荐

