[英]Using a function to free a linked list with double pointer
我很難在單個函數中刪除鏈接中的所有成員。 如果我將其分解,如您在下面看到的那樣,它可以正常工作,但這似乎效率很低,並且想找出正確的方法來做到這一點。 為了釋放所有節點,我需要具有首先釋放除頭之外的所有所有節點的功能,然后具有釋放頭鏈接的功能。 這似乎很容易做到,但我遇到了麻煩。
謝謝您的幫助!
int main() {
struct node *head = NULL;
createList(&head);
//do stuff with list
freeListMembers(head);
freeListHead(&head);
return 0;
}
int createList(struct node **head) {
//create list
return 0;
}
void freeListMembers(struct node *head){
while(head->next != NULL){
head->next = NULL;
free(head->next);
}
return;
}
void freeListHead(struct node **head) {
*head = NULL;
free(*head);
return;
}
這是我要工作但不需要的代碼。 我看到的問題是“ * head-> next;”錯誤 它說“表達式必須具有指向結構或聯合類型的指針”
int main() {
struct node *head = NULL;
createList(&head);
//do stuff with list
freeAllListMembers(&head);
return 0;
}
int createList(struct node **head) {
//create list
return 0;
}
void freeAllListMembers(struct node **head){
while (head != NULL) {
struct node *temp = *head->next;
free(*head);
*head = temp ;
}
return;
}
從您的代碼:
void freeListMembers(struct node *head){
while(head->next != NULL){
head->next = NULL;
free(head->next);
}
return;
}
這將釋放NULL,而不是您的節點*。
釋放列表就像使用指向下一個節點的臨時指針一樣簡單。
while (head) {
node* next = head->next;
free(head);
head = next;
}
根據您的編輯:
void freeAllListMembers(struct node **head){
while (head != NULL) {
struct node *temp = *head->next;
free(*head);
*head = temp ;
}
return;
}
這有幾個錯誤。 應該是while (*head != NULL)
和(*head)->next
。 第一個是邏輯錯誤,因為head將始終為非NULL,第二個是語法錯誤,因為您需要在訪問下一個指針之前取消引用head指針。
這將起作用。 您只需將head的下一個設置為null並釋放head。 現在我們不能移動到第二個元素,因此我們將無法釋放節點,還要檢查基本條件。 希望對您有所幫助
void freeListmembers(node *head){
node *temp=head;
if(head==NULL)//Base condition
return;
while(head->next!=NULL){
temp=head;//Moved temp to head. we will move head to next and free the previous node
head=head->next;
free(temp);
}
free(head);
return;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.