c语言:输入一个数,建立其对应的数字大小的单链表
时间: 2023-05-26 17:02:00 浏览: 50
这是一个例子代码:
```c
#include <stdio.h>
#include <stdlib.h>
typedef struct node {
int data;
struct node *next;
} Node, *ListNode;
ListNode createList(int n) {
int i, x;
ListNode p, q, head;
head = (ListNode) malloc(sizeof(Node));
head->next = NULL;
p = head;
while (n) {
printf("Please input the digit %d:", n--);
scanf("%d", &x);
q = (ListNode) malloc(sizeof(Node));
q->data = x;
q->next = NULL;
p->next = q;
p = q;
}
return head->next;
}
void printList(ListNode l) {
ListNode p = l;
while (p != NULL) {
printf("%d ", p->data);
p = p->next;
}
printf("\n");
}
int main() {
int n;
printf("Please input a number:");
scanf("%d", &n);
ListNode l = createList(n);
printf("The list is: ");
printList(l);
return 0;
}
```
输入一个数,例如`12345`,运行结果如下:
```shell
Please input a number:5
Please input the digit 5:1
Please input the digit 4:2
Please input the digit 3:3
Please input the digit 2:4
Please input the digit 1:5
The list is: 1 2 3 4 5
```
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_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)