在链表中插入和删除节点
Inserting and deleting a node in linked list
我正在学习 C 语言的结构,有两个关于我的代码的问题:
1) 为什么在 insert()
方法中显示这些错误?:
|44|error: incompatible types when returning type 'void *' but 'ListNode' was expected|
|47|error: incompatible types when returning type 'struct Node *' but 'ListNode' was expected|
行中:
if(current -> next == NULL){
printf("The node was not found!");
return NULL; //<<<<<-----------------SHOWS ERROR HERE Line #44
}
和
return newNode; //Line #47
2) 我已经为 delete()
节点编写了代码,但感觉代码可能有问题。我如何通过 C 中的 main()
方法 test/run 程序 :)??
3) 如何在 printList()
方法中打印任何类型的变量?
很抱歉问这些新手问题!
谢谢!
注意:程序可以接受任何数据类型,head*
是一个虚拟节点!
1) 您需要将 NULL
转换为正确的 return 类型。所以,return (ListNode *) NULL
.
您可能想将该函数的 return 类型更改为 ListNode *
。如果你真的想要 return struct
那么 returning NULL
将不起作用,所以你需要 return 一个空的 ListNode struct
.
2) 要测试 delete
是否有效,创建一个非平凡链表,打印内容,调用 delete()
,然后打印内容再次确保节点确实被删除。
如果更新指针出现问题,您可能会在某处得到一个空指针,并且无法正确地遍历列表。
3) 首先,printf
在你的情况下应该有两个参数:more info。第一个是格式字符串,基本上告诉它类型,第二个是实际变量。
您需要知道要打印的类型。您需要将 void *data
转换为正确的指针,然后取消引用。 C无法知道你想要什么。
printf("%d\n", *(int *)mydata);
我正在学习 C 语言的结构,有两个关于我的代码的问题:
1) 为什么在 insert()
方法中显示这些错误?:
|44|error: incompatible types when returning type 'void *' but 'ListNode' was expected|
|47|error: incompatible types when returning type 'struct Node *' but 'ListNode' was expected|
行中:
if(current -> next == NULL){
printf("The node was not found!");
return NULL; //<<<<<-----------------SHOWS ERROR HERE Line #44
}
和
return newNode; //Line #47
2) 我已经为 delete()
节点编写了代码,但感觉代码可能有问题。我如何通过 C 中的 main()
方法 test/run 程序 :)??
3) 如何在 printList()
方法中打印任何类型的变量?
很抱歉问这些新手问题! 谢谢!
注意:程序可以接受任何数据类型,head*
是一个虚拟节点!
1) 您需要将 NULL
转换为正确的 return 类型。所以,return (ListNode *) NULL
.
您可能想将该函数的 return 类型更改为 ListNode *
。如果你真的想要 return struct
那么 returning NULL
将不起作用,所以你需要 return 一个空的 ListNode struct
.
2) 要测试 delete
是否有效,创建一个非平凡链表,打印内容,调用 delete()
,然后打印内容再次确保节点确实被删除。
如果更新指针出现问题,您可能会在某处得到一个空指针,并且无法正确地遍历列表。
3) 首先,printf
在你的情况下应该有两个参数:more info。第一个是格式字符串,基本上告诉它类型,第二个是实际变量。
您需要知道要打印的类型。您需要将 void *data
转换为正确的指针,然后取消引用。 C无法知道你想要什么。
printf("%d\n", *(int *)mydata);