题目描述:
输入一个链表的头节点,从尾到头反过来打印每个节点的值.
测试数据需要用到链表.
解题方法:
算法1:
利用栈保存链表数据
void ReverseShow(LinkList plist)
{
int len = GetLength(plist);//获取链表的长度,即数据个数
int* arr = (int*)malloc(len * sizeof(int));//存放数据的栈
int top = 0;//栈顶指针,当前可以存放数据的下标
for (LNode* p = plist->next; p != NULL; p = p->next)//把链表的数据全部存放到arr中
{
arr[top++] = p->data;
}
while (top > 0)//栈不空
{
printf("%d ",arr[--top]);
}
printf("\n");
free(arr);
}
int main()
{
LNode head;
InitList(&head);
for (int i = 0; i < 20; i++)
Insert_tail(&head,i);
ReverseShow(&head);
return 0;
}
算法2:
static void Reverse(LNode* p)
{
if (p == NULL)
return;
Reverse(p->next);//先输出后面的内容
printf("%d ",p->data);//再输出当前的数据
}
//LinkList是带头节点的,递归输出不带头节点的数据
void ReverseShow(LinkList plist)
{
Reverse(plist->next);
}
int main()
{
LNode head;
InitList(&head);
for (int i = 0; i < 20; i++)
Insert_tail(&head,i);
ReverseShow(&head);
return 0;
}