c语言如何实现链表逆序输出
时间: 2023-09-19 22:03:24 浏览: 105
要实现链表逆序输出,可以使用递归或者迭代的方式。以下是分别使用这两种方法的示例代码。
递归方法:
```c
#include <stdio.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;
}
```
迭代方法:
```c
#include <stdio.h>
struct Node {
int data;
struct Node* next;
};
void reversePrint(struct Node* head) {
struct Node* prev = NULL;
struct Node* current = head;
struct Node* next = NULL;
while (current != NULL) {
next = current->next;
current->next = prev;
prev = current;
current = next;
}
head = prev;
struct Node* temp = head;
while (temp != NULL) {
printf("%d ", temp->data);
temp = temp->next;
}
}
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;
}
```
以上两种方法都能实现链表逆序输出,递归方法通过递归调用实现逆序输出,迭代方法则通过交换链表节点的指针实现逆序输出。