c - C链表不能在开头添加元素
问题描述
我对C相当陌生,我们有一个excersie,我们需要用预定的函数和参数编写一个链表。现在我在列表的开头添加一个新元素时遇到了问题,其他一切正常,这里是语法。
int main(){
Vector3D foo;
foo.x = 521;
foo.y = 2;
foo.z = 3;
VectorList * head;
head = create_VL(NULL, &foo);
insertElementBack(head, &foo);
foo.x = 456;
insertElementBack(head, &foo);
foo.x = 2;
insertElementFront(head, &foo);
print_list(head);
printf("%d\n", size(head));
}
void insertElementFront(VectorList* l, Vector3D* v){
VectorList *previous, *new_VL;
previous = &l;
new_VL = NULL;
new_VL = malloc(sizeof(VectorList));
new_VL -> value = *v;
new_VL -> next = previous;
l = new_VL;
}
VectorList *create_VL(VectorList* l, Vector3D* v) {
VectorList* new_VL = (VectorList*)malloc(sizeof(VectorList));
if(new_VL == NULL)
{
printf("Error creating a new node.\n");
exit(0);
}
new_VL->value = *v;
new_VL->next = l;
return new_VL;
}
void insertElementBack(VectorList* l, Vector3D* v){
VectorList *vl = l;
while( vl -> next != NULL){
vl = vl -> next;
}
VectorList *new_List = create_VL(NULL, v);
vl -> next = new_List;
}
名称和参数不允许更改,我可以使用双指针作为参数解决此问题,但不允许更改。有人可以给我一个提示,我尝试了很多东西,但没有任何效果。
最好的
马丁
解决方案
你真的应该包括定义VectorList
而不是让我们猜测它的结构,但你的问题可能是这样的:
previous = &l;
l
是指向 a 的指针VectorList
。通过这样做&l
,您正在获取指针的地址,而不是VectorList
. 所以当你这样做时
new_VL -> next = previous;
您的next
指针现在指向该指针,而不是VectorList
. 事实上,你没有收到警告吗?不要忽视警告。
您的第二个也是更大的问题是head
没有更新以反映新的头,并且无法使用双指针,您唯一的解决方法是将新的头节点作为返回值从insertElementFront
.
推荐阅读
- ansible - 如何正确使用 failed_when?
- c++ - 输出值是一个不正确且不随输入变化而变化的大整数
- javascript - Vue Cookies .get('token') 返回 null
- javascript - 我如何将 q 的值增加一而无需每次在 Chrome 扩展中打开 popup.js 时重置
- laravel - Laravel Google App Engine - file_put_contents(/tmp/framework/sessions/r3SSHndYkTT0CZA2fU .....)
- parallel-processing - 如何使用 IAsyncEnumerable 进行并行化
- node.js - 如何在反应js中连接mongodb集合?
- reactjs - 如何更改排序可视化工具的 for 循环中每个条的背景颜色?
- python - Python Flask - oserror errno 22 无效参数
- python - 评估 R^2 分数时出错