题解 | #反转链表#
反转链表
https://www.nowcoder.com/practice/75e878df47f24fdc9dc3e400ec6058ca
/*
struct ListNode {
int val;
struct ListNode *next;
ListNode(int x) :
val(x), next(NULL) {
}
};*/
#include <cstddef>
class Solution {
public:
ListNode* ReverseList(ListNode* pHead) {
if(pHead==nullptr) return nullptr;//if null
if(pHead->next== nullptr) return pHead;//if only head
ListNode* last=ReverseList(pHead->next);//从整体功能推测局部
pHead->next->next=pHead;//将phead后一个元素指针逆转
pHead->next=nullptr;//phead设置为空
return last;
}
};
根据Labuladong算法小抄给的递归思路解决。
ReverseList(phead)功能是将整个链表逆转,并返回指向最末结点作为头结点;那ReverseList(phead->next)功能是将除phead结点以外链表逆转,并返回该部分链表的最末结点指针作为头结点;再将phead和剩余链表部分指针进行逆转;将phead指向空,作为末结点即可。
#菜鸟的编程学习#
查看23道真题和解析