大家好,我是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