大家好,我是 C 语言的新手,正在努力学习它。我有一个关于这个链表实现的简单查询,我在很多地方都找到了:
void addNode(node **listhead, int data, int pos){
if(pos<=0 || pos > length(*listhead)+1){
printf("Invalid position provided, there are currently %d nodes in the list \n", length(*listhead));
return;
}else{
node *current = *listhead;
node *newNode = (node*)malloc(sizeof(node));
if(newNode == NULL){
printf("Memory allocation error\n");
return;
}
newNode->data = data;
newNode->next = NULL;
if (current == NULL){
*listhead = newNode;
return;
}else{
int i = 0;
while(current->next != NULL && i < pos-1){
++i;
current = current->next;
}
if(current->next == NULL){
current->next = newNode;
}
if(i == pos-1){
newNode->next = current->next;
current->next = newNode;
}
}
}
}
int main(){
node *head = NULL;
node **headref = &head;
addNode(headref, 1, 1);
addNode(headref, 2, 2);
addNode(headref, 3, 3);
printList(head);
return 0;
}
我的查询在这里我们正在创建一个指向指向 NULL 的指针的指针。此代码有效,但是我想知道这是否是一个好习惯。如果不是,我应该如何创建我的头指针并将其引用传递给 addNode 函数。