用c语言从尾到头输出单链表
时间: 2024-05-05 20:17:22 浏览: 33
下面是用C语言从尾到头输出单链表的示例代码:
```c
#include <stdio.h>
#include <stdlib.h>
// 定义链表节点结构体
typedef struct ListNode {
int val;
struct ListNode *next;
} ListNode;
// 将一个新节点插入到链表的末尾
void insert(ListNode **head, int val) {
ListNode *newNode = (ListNode*)malloc(sizeof(ListNode));
newNode->val = val;
newNode->next = NULL;
if (*head == NULL) {
*head = newNode;
} else {
ListNode *p = *head;
while (p->next != NULL) {
p = p->next;
}
p->next = newNode;
}
}
// 从尾到头输出链表
void printListReverse(ListNode *head) {
if (head == NULL) {
return;
}
printListReverse(head->next);
printf("%d ", head->val);
}
int main() {
ListNode *head = NULL;
insert(&head, 1);
insert(&head, 2);
insert(&head, 3);
insert(&head, 4);
insert(&head, 5);
printf("The original list is: ");
ListNode *p = head;
while (p != NULL) {
printf("%d ", p->val);
p = p->next;
}
printf("\n");
printf("The list in reverse order is: ");
printListReverse(head);
printf("\n");
return 0;
}
```
输出结果为:
```
The original list is: 1 2 3 4 5
The list in reverse order is: 5 4 3 2 1
```