序打印链表?
在C语言中,可以使用递归或迭代的方式来实现逆序打印链表。
递归方法:
递归方法是通过递归调用函数本身来实现的。具体步骤如下:
以下是一个使用递归方法打印链表的示例代码:
#include <stdio.h>
#include <stdlib.h>
typedef struct Node {
int data;
struct Node* next;
} Node;
void printListReverse(Node* head) {
if (head == NULL) {
return;
}
printListReverse(head->next);
printf("%d ", head->data);
}
int main() {
Node* head = NULL;
Node* second = NULL;
Node* third = NULL;
head = (Node*)malloc(sizeof(Node));
second = (Node*)malloc(sizeof(Node));
third = (Node*)malloc(sizeof(Node));
head->data = 1;
head->next = second;
second->data = 2;
second->next = third;
third->data = 3;
third->next = NULL;
printf("Original list: ");
Node* current = head;
while (current != NULL) {
printf("%d ", current->data);
current = current->next;
}
printf("\nReversed list: ");
printListReverse(head);
return 0;
}
输出结果为:
Original list: 1 2 3
Reversed list: 3 2 1
迭代方法:
迭代方法是通过使用一个辅助栈来实现的。具体步骤如下:
以下是一个使用迭代方法打印链表的示例代码:
#include <stdio.h>
#include <stdlib.h>
typedef struct Node {
int data;
struct Node* next;
} Node;
void printListReverse(Node* head) {
Node* stack = NULL;
Node* current = head;
while (current != NULL) {
Node* newNode = (Node*)malloc(sizeof(Node));
newNode->data = current->data;
newNode->next = stack;
stack = newNode;
current = current->next;
}
printf("Reversed list: ");
while (stack != NULL) {
printf("%d ", stack->data);
Node* temp = stack;
stack = stack->next;
free(temp);
}
}
int main() {
Node* head = NULL;
Node* second = NULL;
Node* third = NULL;
head = (Node*)malloc(sizeof(Node));
second = (Node*)malloc(sizeof(Node));
third = (Node*)malloc(sizeof(Node));
head->data = 1;
head->next = second;
second->data = 2;
second->next = third;
third->data = 3;
third->next = NULL;
printf("Original list: ");
Node* current = head;
while (current != NULL) {
printf("%d ", current->data);
current = current->next;
}
printListReverse(head);
return 0;
}
输出结果为:
Original list: 1 2 3
Reversed list: 3 2 1
推荐的腾讯云相关产品和产品介绍链接地址:
领取专属 10元无门槛券
手把手带您无忧上云