c语言链表传字符串例子
时间: 2023-11-04 16:04:38 浏览: 38
以下是一个简单的 C 语言链表传字符串的例子:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
// 定义结构体
struct node {
char *str;
struct node *next;
};
// 创建节点
struct node* create_node(char *str) {
struct node *new_node = malloc(sizeof(struct node));
new_node->str = malloc(strlen(str) + 1);
strcpy(new_node->str, str);
new_node->next = NULL;
return new_node;
}
// 插入节点
void insert_node(struct node **head, char *str) {
struct node *new_node = create_node(str);
if (*head == NULL) {
*head = new_node;
} else {
struct node *curr = *head;
while (curr->next != NULL) {
curr = curr->next;
}
curr->next = new_node;
}
}
// 打印链表
void print_list(struct node *head) {
while (head != NULL) {
printf("%s ", head->str);
head = head->next;
}
printf("\n");
}
int main() {
struct node *head = NULL;
insert_node(&head, "Hello");
insert_node(&head, "world");
insert_node(&head, "!");
print_list(head);
return 0;
}
```
以上代码演示了如何创建一个简单的链表来存储字符串。在这个例子中,我们定义了一个结构体 `node`,它包含一个字符串指针 `str` 和一个指向下一个节点的指针 `next`。通过 `create_node` 函数创建节点,通过 `insert_node` 函数将节点插入链表中,通过 `print_list` 函数打印链表中的字符串。在 `main` 函数中,我们创建了一个空链表 `head`,并通过 `insert_node` 函数将三个字符串插入链表中,最后通过 `print_list` 函数打印链表中的字符串。