用C语言写一个将单链表逆序输出的程序
时间: 2023-05-18 10:07:14 浏览: 165
以下是用C语言写一个将单链表逆序输出的程序的代码:
```c
#include <stdio.h>
#include <stdlib.h>
struct Node {
int data;
struct Node* next;
};
void reversePrint(struct Node* head) {
if (head == NULL) {
return;
}
reversePrint(head->next);
printf("%d ", head->data);
}
int main() {
struct Node* head = NULL;
struct Node* second = NULL;
struct Node* third = NULL;
head = (struct Node*)malloc(sizeof(struct Node));
second = (struct Node*)malloc(sizeof(struct Node));
third = (struct Node*)malloc(sizeof(struct Node));
head->data = 1;
head->next = second;
second->data = 2;
second->next = third;
third->data = 3;
third->next = NULL;
reversePrint(head);
return 0;
}
```
这个程序使用递归的方式将单链表逆序输出。首先判断链表是否为空,如果不为空,就递归调用函数,将链表的下一个节点作为参数传入,直到链表的最后一个节点。然后再依次输出每个节点的值。
阅读全文