从尾到头打印单链表
思路:自己画一个简单的链表有助于理解,先来分析打印一次的过程,cur 是用来遍历链表用的。就这个题来说,我么们首先要打印5,也就是当cur->next = NULL时,打印cur->data的值。第二次,要打印4,也就是当cur->next = 5。所以我们需要用一个指针记录每一趟的结尾,并且每一趟都需要从头开始,所以需要一个指针记录头的位置。下面看代码具体实现。
//链表面试题.c
#include "链表面试题.h"
#include <stdio.h>
//非递归写法
void PrintReverse(ListNode* first) {
ListNode* end = NULL;
while (end != first) {
ListNode* cur = first; //每趟循环都需要重新设定
while (cur->next != end) {
cur = cur->next;
}
//该趟的结尾
printf("%d ", cur->data);
end = cur; //将end指针指向此时的cur
}
}
//递归写法
void PrintReverseRecursion(ListNode* first)
{
#if 0
if (first->next == NULL) {
printf("%d ", first->data);
}
//
else {
PrintReverseRecursion(first->next);
printf("%d ", first->data);
}
#endif
//对上面写法的改进
if (first == NULL) {
return;
}
else {
PrintReverseRecursion(first->next);
printf("%d ", first->data);
}
}
void TestPrintReverse()
{
printf("非递归写法:");
ListNode *first = NULL;
ListPushBack(&first, 1);
ListPushBack(&first, 2);
ListPushBack(&first, 3);
ListPushBack(&first, 4);
ListPushBack(&first, 5);
PrintReverse(first);
printf("\n");
}
void TestPrintReverse2()
{
printf("递归写法: ");
ListNode *first = NULL;
ListPushBack(&first, 1);
ListPushBack(&first, 2);
ListPushBack(&first, 3);
ListPushBack(&first, 4);
ListPushBack(&first, 5);
PrintReverseRecursion(first);
}