题目:输入一个链表的头结点,从尾到头反过来输出每个结点的值。链表结点定义如下:
struct ListNode
{
int m_nKey;
ListNode* m_pNext;
};
分析:这是一道很有意思的面试题。
该题以及它的变体经常出现在各大公司的面试、笔试题中。
#include <stdio.h>
#include <stdlib.h>
struct ListNode {
int m_nKey;
struct ListNode* m_pNext;
};
void create_list(struct ListNode **pLn, int *arr, int i, int len)
{
struct ListNode *n;
if (i >= len) {
*pLn = NULL;
return;
}
n = (struct ListNode *) malloc(sizeof(struct ListNode));
n->m_nKey = arr[i];
*pLn = n;
i++;
create_list(&(n->m_pNext), arr, i , len);
}
void show(struct ListNode *ln)
{
if (ln == NULL) {
return;
}
show(ln->m_pNext);
printf("%d ", ln->m_nKey);
}
int main()
{
int a[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
struct ListNode *list;
create_list(&list, a, 0, 10);
printf("---------------\n");
show(list);
printf("\n---------------\n");
return 0;
}
链表反转输出:从尾到头的高效算法实现
本文详细介绍了如何使用递归和迭代两种方式来反转链表并从尾到头输出节点值,包括链表结构定义、算法实现及代码示例。
1304

被折叠的 条评论
为什么被折叠?



