用c语言写一个程序,任意输入几个数,用链表逆序输出
时间: 2024-03-19 22:45:32 浏览: 69
好的,下面是用C语言实现的程序:
```c
#include <stdio.h>
#include <stdlib.h>
struct node {
int data;
struct node *next;
};
void add_node(struct node **head, int data) {
struct node *new_node = (struct node *)malloc(sizeof(struct node));
new_node->data = data;
new_node->next = NULL;
if (*head == NULL) {
*head = new_node;
return;
}
struct node *temp = *head;
while (temp->next != NULL) {
temp = temp->next;
}
temp->next = new_node;
}
void reverse_print(struct node *head) {
if (head == NULL) {
return;
}
reverse_print(head->next);
printf("%d ", head->data);
}
int main() {
int n, data;
struct node *head = NULL;
printf("请输入要输入的数字个数:");
scanf("%d", &n);
printf("请输入%d个数字:", n);
for (int i = 0; i < n; i++) {
scanf("%d", &data);
add_node(&head, data);
}
printf("逆序输出的结果为:");
reverse_print(head);
return 0;
}
```
运行结果:
```
请输入要输入的数字个数:5
请输入5个数字:1 2 3 4 5
逆序输出的结果为:5 4 3 2 1
```
阅读全文