[英]is this linkedlist code a good practice?
大家好,我是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函數。
建議的替代方案:
int main() {
node *head = addNode(NULL, 1, 1);
node *current = head;
current = addNode(current, 2, 2);
current = addNode(current, 3, 3);
printList(head);
return 0;
}
換一種說法:
1)addNode()成為一個函數,它將當前值作為參數(因此它不必遍歷整個列表只是為了添加一個新元素)...
2)...並返回指向新節點的指針。
3)這意味着在程序的任何一點你都可以訪問以下任何一個:a)列表頭,b)前一個指針(在“添加”之前)和/或c)下一個指針(在添加之后)。
我們將一個雙指針傳遞給addNode()用於需要更新headref指針的情況。 對於這種情況,使用“addNode(headref,1,1);”,addNode很可能將malloced元素的地址存儲在headref中的addNode()內。 如果你將headref作為指針傳遞,那么在調用后headref將繼續指向main中的地址,你將丟失malloced地址。
對於單鏈表,它實際上是一種很好的做法,它簡化了addNode實現。 我想對addNode(node_x, 1, 1)
的調用將在node_x
之前添加一個節點。 如果只傳遞指向node_x
的指針。 然后,函數將需要遍歷整個列表並在node_x
之前找到節點並修改其指向新構造節點的指針。 如果你將一個指針傳遞給指針,讓我們說node** p
那么該函數只需要將新節點的地址分配給*p
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.