题目:单链表的反转算法
struct ListNode
{
ListNode(int x ): val(x), next(NULL){}
int val;
ListNode* next;
};
ListNode* ReverseList(ListNode* pHead)
struct ListNode
{
ListNode(int x ): val(x), next(NULL){}
int val;
ListNode* next;
};
ListNode* ReverseList(ListNode* pHead)
{
if(pHead == NULL)
{
return NULL;
}
//一、指针的初始化阶段
ListNode* pPre = pHead;
ListNode* pCur = pPre->next;
ListNode* pNext = NULL;
//二、反转单链表的核心代码
while (pCur != NULL)
{
pNext = pCur->next;//缓存next指针
pCur->next = pPre;//单链表反转
pPre = pCur;//pPre指针后移
pCur = pNext;//pCur指针后移
}
//三、处理并返回头指针
pHead = NULL;//原头节点next变为空
return pPre;
}
测试代码:
void BianLi(ListNode* pHead)
{
ListNode* pCur = pHead;
while(pCur!=NULL)
{
cout<<pCur->val<<endl;
pCur = pCur->next;
}
}
void main()
{
ListNode l1(1);
ListNode l2(2);
ListNode l3(3);
l1.next = &l2;
l2.next = &l3;
l3.next = NULL;
ListNode* pHead = &l1;
BianLi(pHead);
pHead = ReverseList(pHead);
BianLi(pHead);
}
参考博客:https://blog.csdn.net/ding977921830/article/details/52751490 单链表的反转