大家好,我是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函数。
这不是一个链接列表实现。这是一个链表的用法。并且使用NULL指针没有问题(它们出于某种原因在语言中),但是如果没有更多的上下文和实际的**相关**代码,很难分辨出所有这些都在做什么。 – 2013-09-27 04:41:06
如果你不喜欢'headref',你也可以使用'addNode(&head,1,1)'。一般来说,这个代码并没有一个特定的坏习惯。 –
我也用addNode函数更新了代码。感谢回复,我想我明白了,只是对指针有愚蠢的担心。再次感谢。 – user1772218