倒叙打印链表
非递归
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/1f71b8f7d61c647ae2ada0a2454530c0.png)
// 倒叙打印链表
void ReversePrint(SListNode *pFirst)
{
SListNode *cur = NULL;
SListNode *last = NULL;
while (last!=pFirst)
{
cur = pFirst;
while (cur->Next != last)
{
cur = cur->Next;
}
printf("%d-->", cur->data);
last = cur;
}
printf("NULL\n");
}
递归
//倒叙打印链表
void ReversePrint(SListNode *pFirst)
{
if (pFirst == NULL); {
return;
}//递归结束条件一
if (pFirst->Next == NULL) {
printf("%d-->", pFirst->data);
return;
}//递归结束条件二
ReversePrint(pFirst->Next);
printf("%d-->", pFirst->data);
}
逆置/反转单链表
头删尾插
//逆置/反转单链表
SListNode * ReverseList(SListNode *pFirst)
{
SListNode *Result = NULL;
SListNode *cur = pFirst;//一直指向原来链表的第一个节点
SListNode *node;
while (cur != NULL) {
//从原链表头删
node = cur;
cur = cur->Next;
//头插到结果链表
node->Next = Result;
Result = node;
}
SListPrint(Result);
}
三个结点
![逆置单链表](https://i-blog.csdnimg.cn/blog_migrate/b538cbdb521d3e572f5d89232e0004e2.png)
// 逆置/反转单链表
SListNode * ReverseList(SListNode *pFirst)
{
if (pFirst == NULL && pFirst->Next == NULL) {
return;
}
SListNode *p1, *p2, *p3;
p1 = NULL;
p2 = pFirst;
p3 = pFirst->Next;
while (p2 != NULL) {
p2->Next = p1;
p1 = p2;
p2 = p3;
if (p3 != NULL) {
p3 = p3->Next;
}
}
SListPrint(p1);
}