设链表结点结构已经给出,试编写链表插入函数Insert将实现链表末尾添加数据,再编写函数Print,实现链表中链表数据打印,编写Destroy函数,实现链表的销毁释放,并在main函数中写出完整的调用过程。 typedef struct node { char Name[20]; struct node *Next; }Node;
时间: 2024-03-22 07:37:41 浏览: 14
好的,我已经记录了您的要求。下面是实现链表插入、打印、销毁函数的示例代码:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct node {
char Name[20];
struct node *Next;
} Node;
// 链表插入函数
void Insert(Node **head, char *name) {
Node *new_node = (Node*)malloc(sizeof(Node));
strcpy(new_node->Name, name);
new_node->Next = NULL;
if (*head == NULL) {
*head = new_node;
} else {
Node *p = *head;
while (p->Next != NULL) {
p = p->Next;
}
p->Next = new_node;
}
}
// 链表打印函数
void Print(Node *head) {
Node *p = head;
while (p != NULL) {
printf("%s ", p->Name);
p = p->Next;
}
printf("\n");
}
// 链表销毁函数
void Destroy(Node **head) {
Node *p = *head;
while (p != NULL) {
Node *q = p->Next;
free(p);
p = q;
}
*head = NULL;
}
int main() {
Node *head = NULL;
Insert(&head, "Alice");
Insert(&head, "Bob");
Insert(&head, "Charlie");
Print(head);
Destroy(&head);
return 0;
}
```
在上面的代码中,我们使用了双重指针来解决传递头指针时可能会改变指针指向的问题。在Insert函数中,我们创建一个新的结点,并且在链表的末尾添加该结点。在Print函数中,我们遍历整个链表并打印每个结点的Name字段。在Destroy函数中,我们遍历整个链表并释放每个结点的内存空间,最后将头指针赋值为NULL。在main函数中,我们调用Insert函数三次来添加三个结点,然后调用Print函数来打印整个链表,最后调用Destroy函数来销毁链表并释放内存空间。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![gz](https://img-home.csdnimg.cn/images/20210720083447.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![gz](https://img-home.csdnimg.cn/images/20210720083447.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)