写一段c语言单链表节点逐个释放程序
时间: 2024-05-21 10:10:23 浏览: 75
#include <stdio.h>
#include <stdlib.h>
struct Node {
int data;
struct Node* next;
};
void freeList(struct Node* head) {
struct Node* tmp;
while (head != NULL) {
tmp = head;
head = head->next;
free(tmp);
}
}
int main() {
struct Node* head = NULL;
struct Node* second = NULL;
struct Node* third = NULL;
// Allocate 3 nodes in the heap
head = (struct Node*)malloc(sizeof(struct Node));
second = (struct Node*)malloc(sizeof(struct Node));
third = (struct Node*)malloc(sizeof(struct Node));
/* Three blocks have been allocated dynamically.
We have pointers to these three blocks as head,
second and third
head second third
| | |
| | |
+---+------+ +----+-----+ +----+-----+
| # | data | | # | data | | # | data |
+---+------+ +----+-----+ +----+-----+
*/
head->data = 1; // assign data in first node
head->next = second; // Link first node with second
second->data = 2; // assign data to second node
second->next = third;
third->data = 3; // assign data to third node
third->next = NULL;
freeList(head); // Release memory allocated by nodes
return 0;
}
阅读全文