请以C语言实现双向链表的清空
时间: 2023-10-31 07:06:42 浏览: 97
好的,以下是以C语言实现双向链表的清空的代码:
```
#include<stdio.h>
#include<stdlib.h>
typedef struct node {
int data;
struct node* next;
struct node* prev;
} Node;
Node* head = NULL;
void insert(int value) {
Node* newNode = (Node*)malloc(sizeof(Node));
newNode->data = value;
newNode->prev = NULL;
newNode->next = head;
if (head != NULL) {
head->prev = newNode;
}
head = newNode;
}
void clear() {
Node* current = head;
Node* next;
while (current != NULL) {
next = current->next;
free(current);
current = next;
}
head = NULL;
}
int main() {
insert(10);
insert(20);
insert(30);
printf("Before clear: ");
Node* current = head;
while (current != NULL) {
printf("%d ", current->data);
current = current->next;
}
clear();
printf("\nAfter clear: ");
current = head;
while (current != NULL) {
printf("%d ", current->data);
current = current->next;
}
return 0;
}
```
这个代码实现了双向链表的插入,然后通过 clear() 函数将链表清空。在这个函数中,我们使用 while 循环遍历链表并释放所有节点,并将头节点设置为 NULL 表示链表为空。
注意,此处清空链表的方式并不是直接将头指针置为 NULL,而是通过循环遍历释放每个节点的方式清除整个链表。这样做是为了避免内存泄漏。
阅读全文