**C 语言:逆序输出链表**185


链表是一种常见的数据结构,它由一系列通过指针连接起来的节点组成。每个节点都包含一个数据元素和指向下一个节点的指针。在某些情况下,我们需要逆序输出链表中的元素。这篇文章将介绍在 C 语言中逆序输出链表的算法和实现。

算法

逆序输出链表的算法主要有两种方法:

递归方法



基本情况:如果链表为空或仅包含一个节点,则直接输出元素。
递归情况:调用函数递归输出链表的剩余部分,然后输出当前元素。

迭代方法



创建一个空的栈。
依次将链表中的元素压入栈中。
依次从栈中弹出元素并输出。

实现

递归方法


```c
#include
#include
struct Node {
int data;
struct Node *next;
};
// 递归函数,逆序输出链表
void print_list_reverse(struct Node *head) {
if (head == NULL) {
return;
}
print_list_reverse(head->next);
printf("%d ", head->data);
}
```

迭代方法


```c
#include
#include
struct Node {
int data;
struct Node *next;
};
// 栈结构
struct Stack {
struct Node *top;
};
// 创建一个栈
struct Stack *create_stack() {
struct Stack *stack = malloc(sizeof(struct Stack));
stack->top = NULL;
return stack;
}
// 入栈
void push(struct Stack *stack, struct Node *node) {
node->next = stack->top;
stack->top = node;
}
// 出栈
struct Node *pop(struct Stack *stack) {
if (stack->top == NULL) {
return NULL;
}
struct Node *node = stack->top;
stack->top = stack->top->next;
return node;
}
// 迭代方法,逆序输出链表
void print_list_reverse_iterative(struct Node *head) {
struct Stack *stack = create_stack();
while (head != NULL) {
push(stack, head);
head = head->next;
}
while (stack->top != NULL) {
struct Node *node = pop(stack);
printf("%d ", node->data);
}
}
```

测试```c
#include
#include
struct Node {
int data;
struct Node *next;
};
int main() {
struct Node *head = NULL;

// 创建链表
for (int i = 1; i data = i;
new_node->next = head;
head = new_node;
}

// 使用递归方法逆序输出链表
printf("递归方法逆序输出:");
print_list_reverse(head);
printf("");

// 使用迭代方法逆序输出链表
printf("迭代方法逆序输出:");
print_list_reverse_iterative(head);
printf("");

return 0;
}
```

输出```
递归方法逆序输出:5 4 3 2 1
迭代方法逆序输出:5 4 3 2 1
```

2024-10-29


上一篇:C 语言中的宏函数

下一篇:C语言函数调用输出