编写算法实现链表的逆序打印
要求:
- 使用递归或者栈结构实现,不要改变链表的结构,从尾输出到头每个节点的值
#include <stdio.h>
#include <stdlib.h>
// 链表节点定义
typedef struct ListNode {
int data; // 节点数据
struct ListNode* next; // 指向下一个节点的指针
} ListNode;
/**
* 递归方式逆序打印链表
* @param current 当前遍历到的节点
*/
void reversePrintRecursive(ListNode* current) {
if (current == NULL) {
return; // 递归基:空链表或到达链表末尾
}
// 先递归打印后续节点
reversePrintRecursive(current->next);
// 再打印当前节点(这样就实现了逆序)
printf("%d ", current->data);
}
/**
* 创建新节点
* @param value 节点值
* @return 新创建的节点指针
*/
ListNode* createNode(int value) {
ListNode* newNode = (ListNode*)malloc(sizeof(ListNode));
if (newNode == NULL) {
printf("内存分配失败!\n");
exit(1);
}
newNode->data = value;
newNode->next = NULL;
return newNode;
}
/**
* 在链表尾部添加新节点
* @param head 链表头指针
* @param value 要添加的值
* @return 链表头指针
*/
ListNode* appendNode(ListNode* head, int value) {
ListNode* newNode = createNode(value);
if (head == NULL) {
return newNode; // 如果链表为空,新节点就是头节点
}
ListNode* current = head;
while (current->next != NULL) {
current = current->next;
}
current->next = newNode;
return head;
}
/**
* 打印链表(正序)
* @param head 链表头指针
*/
void printList(ListNode* head) {
ListNode* current = head;
printf("链表正序: ");
while (current != NULL) {
printf("%d", current->data);
if (current->next != NULL) {
printf(" -> ");
}
current = current->next;
}
printf("\n");
}
/**
* 释放链表内存
* @param head 链表头指针
*/
void freeList(ListNode* head) {
ListNode* current = head;
while (current != NULL) {
ListNode* temp = current;
current = current->next;
free(temp);
}
}
// 测试代码
int main() {
ListNode* head = NULL;
// 创建链表: 1 -> 2 -> 3 -> 4 -> 5
head = appendNode(head, 1);
head = appendNode(head, 2);
head = appendNode(head, 3);
head = appendNode(head, 4);
head = appendNode(head, 5);
// 打印原始链表
printList(head);
// 逆序打印链表
printf("链表逆序: ");
reversePrintRecursive(head);
printf("\n");
// 释放内存
freeList(head);
return 0;
}
评论区