#include <stdio.h>
#include <stdlib.h>
typedef struct Node {
int data;
struct Node *next;
} Node;
void reverse_print_list(Node *head)
{
if(head == NULL)
return;
print_list(head->next);
printf("%d ", head->data);
}
int main()
{
Node *head = malloc(sizeof(Node));
head->data = rand() % 100;
head->next = NULL;
Node *temp = head;
for (int i = 0; i < 9; i ) {
Node* new_node = malloc(sizeof(Node));
new_node->data = rand() % 100;
new_node->next = NULL;
temp->next = new_node;
temp = temp->next;
}
temp = head;
printf("Original list : \n");
while (temp != NULL) {
printf("%d ", temp->data);
temp = temp->next;
}
printf("\n---------------------------\n");
reverse_print_list(head);
free(head);
free(temp);
return 0;
}
在上面的代碼中,在 main() 的 for 回圈中,我為鏈表的新節點動態分配記憶體,并將每個新創建的節點附加到串列中的最后一個節點。但這似乎會導致記憶體泄漏,因為我沒有在回圈結束時釋放這些節點,因為我需要這些節點存在于回圈之外。如何釋放我在 for 回圈中創建的節點?運行另一個回圈從head保存所有節點的地址開始,然后運行另一個回圈手動 free() 所有這些地址似乎很乏味。還有其他方法嗎?謝謝。
uj5u.com熱心網友回復:
只需洗掉頭節點并替換head為其后繼節點即可。重復直到head變空。請注意,您必須在呼叫 free() 之前備份next指標。
int main()
{
Node *head = malloc(sizeof(Node));
head->data = rand() % 100;
head->next = NULL;
... build and print your list ...
while (head)
{
Node * remainingChain = head->next;
free(head);
head = remainingChain;
}
return 0;
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/424478.html
