编写一个C程序,输入N个单词,建一个单链表,然后从头节点开始遍历输出,递归实现。例如输入3 one two three输出Three two one,输出结果每个都自己占一行
时间: 2024-03-20 11:44:27 浏览: 24
好的,以下是实现该功能的 C 语言程序:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
// 定义单链表节点结构体
struct Node {
char word[50];
struct Node *next;
};
// 递归遍历输出单链表
void print_list_recursive(struct Node *node) {
if (node == NULL) {
return;
}
print_list_recursive(node->next);
printf("%s\n", node->word);
}
int main() {
int n;
char word[50];
struct Node *head = NULL;
struct Node *tail = NULL;
printf("请输入单词个数:");
scanf("%d", &n);
for (int i = 0; i < n; i++) {
printf("请输入第 %d 个单词:", i + 1);
scanf("%s", word);
// 创建新节点
struct Node *node = (struct Node *)malloc(sizeof(struct Node));
strcpy(node->word, word);
node->next = NULL;
// 将新节点插入单链表
if (head == NULL) {
head = node;
tail = node;
} else {
tail->next = node;
tail = node;
}
}
printf("递归遍历输出单链表:\n");
print_list_recursive(head);
return 0;
}
```
程序运行时,先输入单词个数,再输入每个单词,程序会将这些单词建立成一个单链表,并递归遍历输出单链表,输出结果每个都自己占一行。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.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)
![](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)