编写一个C程序,输入N个单词,建一个单链表,然后从头节点开始遍历输出,递归实现。例如输入3 one two three(注意这四个每个占一行)输出Three two one(注意这四个每个占一行))
时间: 2024-03-20 16:43:37 浏览: 6
好的,下面是实现该功能的C语言代码:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
// 定义链表节点结构体
struct Node {
char* word; // 单词
struct Node* next; // 下一个节点
};
// 递归输出链表
void printListRecursively(struct Node* node) {
if (node == NULL) {
return;
}
printListRecursively(node->next);
printf("%s\n", node->word);
}
int main() {
int n; // 单词数量
scanf("%d", &n);
struct Node* head = NULL; // 链表头节点
// 读入单词并创建链表
for (int i = 0; i < n; i++) {
char* word = (char*)malloc(sizeof(char) * 100); // 假设单词长度不超过100
scanf("%s", word);
struct Node* node = (struct Node*)malloc(sizeof(struct Node));
node->word = word;
node->next = head;
head = node;
}
// 递归输出链表
printListRecursively(head);
// 释放链表节点和单词所占用的内存
while (head != NULL) {
struct Node* next = head->next;
free(head->word);
free(head);
head = next;
}
return 0;
}
```
注意,本程序在读入每个单词时,使用了动态内存分配函数`malloc()`,这是为了避免在栈上分配过大的空间导致栈溢出。同时,在释放链表节点和单词所占用的内存时,要确保在释放节点之前先释放单词的内存。