用C语言编写一i个完整程序反向输出一个链表。
时间: 2024-05-11 10:17:40 浏览: 111
链表反转的C语言程序
好的,以下是代码:
```c
#include <stdio.h>
#include <stdlib.h>
// 定义链表结构体
typedef struct Node {
int data;
struct Node* next;
} Node;
// 反转链表函数
Node* reverseList(Node* head) {
Node* prev = NULL;
Node* curr = head;
Node* next = NULL;
while (curr != NULL) {
next = curr->next;
curr->next = prev;
prev = curr;
curr = next;
}
return prev;
}
// 输出链表函数
void printList(Node* head) {
Node* curr = head;
while (curr != NULL) {
printf("%d ", curr->data);
curr = curr->next;
}
printf("\n");
}
int main() {
// 初始化链表
Node* head = malloc(sizeof(Node));
head->data = 1;
head->next = malloc(sizeof(Node));
head->next->data = 2;
head->next->next = malloc(sizeof(Node));
head->next->next->data = 3;
head->next->next->next = NULL;
// 输出原始链表
printf("Original list: ");
printList(head);
// 反转链表
Node* reversed = reverseList(head);
// 输出反转后的链表
printf("Reversed list: ");
printList(reversed);
return 0;
}
```
希望这个程序可以帮助你!
阅读全文