运用C语言,输入n个单词,建立单链表,然后从节点开始遍历输出,用递归实现
时间: 2024-03-21 16:40:03 浏览: 12
好的,我会尽力回答你的问题。
首先,我们需要定义一个单链表节点的结构体:
```c
struct Node {
char word[50];
struct Node *next;
};
```
然后,我们可以使用一个循环来读取n个单词,并将它们添加到单链表中:
```c
int n;
printf("请输入单词个数:");
scanf("%d", &n);
struct Node *head = NULL;
struct Node *tail = NULL;
for (int i = 0; i < n; i++) {
char word[50];
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;
}
}
```
接下来,我们可以使用递归函数来遍历单链表并输出每个节点的单词:
```c
void traverse(struct Node *node) {
if (node == NULL) {
return;
}
printf("%s ", node->word);
traverse(node->next);
}
```
最后,我们可以在主函数中调用上面的代码:
```c
int main() {
// 读取n个单词并建立单链表
...
// 遍历单链表并输出单词
traverse(head);
return 0;
}
```
这样,我们就完成了用C语言输入n个单词,建立单链表,然后从节点开始遍历输出,用递归实现的问题。