[剑指Offer]24-反转链表

时间:2023-03-09 22:23:36
[剑指Offer]24-反转链表

题目链接

https://www.nowcoder.com/practice/75e878df47f24fdc9dc3e400ec6058ca?tpId=13&tqId=11168&tPage=1&rp=1&ru=%2Fta%2Fcoding-interviews&qru=%2Fta%2Fcoding-interviews%2Fquestion-ranking

题意

输入一个链表,反转链表后,输出新链表的表头。

解题思路

每次要记录三个指针,当前节点,前面节点,后面节点。

从前往后反转,即可。

代码

/*struct ListNode {
int val;
struct ListNode *next;
ListNode(int x) :
val(x), next(NULL) {
}
};*/ class Solution {
public:
ListNode* ReverseList(ListNode* pHead) {
if(!pHead){
return nullptr;
}
if(!pHead->next){
return pHead;
} ListNode* pCurrent;
ListNode* pBefore;
ListNode* pBehind; pCurrent=pHead;
while(pCurrent->next){
if(pCurrent==pHead){
pBefore=nullptr;
}
//更新当前节点
pBehind=pCurrent->next;
pCurrent->next=pBefore; //初始化下一个节点
pBefore=pCurrent;
pCurrent=pBehind;
}
pCurrent->next=pBefore;
return pCurrent;
}
};