C语言编程:【问题描述】 输入一组整数,以-1作为结束条件,用递归方法创建单链表,打印链表 【输入形式】 一组整数,以-1作为结束条件(-1不包含在单链表中) 【输出形式】 打印链表 【样例输入】 1 2 3 -1 【样例输出】 1 2 3
时间: 2024-02-28 15:57:20 浏览: 31
好的,下面是一个简单的C语言递归程序示例:
```c
#include <stdio.h>
#include <stdlib.h>
struct Node
{
int data;
struct Node *next;
};
struct Node* createList()
{
int data;
scanf("%d", &data);
if (data == -1)
{
return NULL;
}
else
{
struct Node *p = (struct Node*)malloc(sizeof(struct Node));
p->data = data;
p->next = createList();
return p;
}
}
void printList(struct Node *p)
{
if (p != NULL)
{
printf("%d ", p->data);
printList(p->next);
}
}
int main()
{
struct Node *head = createList();
printList(head);
return 0;
}
```
在这个示例中,我们定义了一个结构体`Node`来表示单链表的每个节点,包含一个整型数据`data`和一个指向下一个节点的指针`next`。然后,我们使用递归方法创建单链表和打印链表。
在`createList()`函数中,我们首先读取输入的整数,如果为-1,则返回NULL表示单链表创建结束;否则,我们创建一个新的节点并将输入的整数存储在节点的数据域中,同时递归调用`createList()`函数来创建下一个节点,并将其地址存储在当前节点的指针域中,最后返回当前节点的地址。
在`printList()`函数中,我们首先判断当前节点是否为空,如果不为空,则输出当前节点的数据域,并递归调用`printList()`函数来输出下一个节点。
在主函数中,我们首先调用`createList()`函数来创建单链表,并将其头节点的地址存储在`head`指针中,然后调用`printList()`函数来打印链表中的所有节点的数据域。
需要注意的是,在实际应用中,我们需要对输入数据进行合法性检查,以确保输入的整数都是合法的。另外,我们还需要对单链表进行内存管理,避免内存泄漏和内存溢出等问题。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.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)