剑指offer:反转链表
#include <cstddef>
class Solution {
public:
ListNode* ReverseList(ListNode* pHead){
if(pHead == nullptr || pHead->next ==nullptr) return pHead;
ListNode* ans = ReverseList(pHead->next);
pHead ->next->next = pHead;
pHead ->next = nullptr;
return ans;
}
};
先判断pHead和这个头节点的下一个为空时,输出本身;在接着从头到尾递归,最后一个节点为头结点,定义为ans,让当前结点的下一个结点的下一个结点指针指向当前指针,同时,让当前指针的下一个节点的指针指向空,最后输出ans!!!
#剑指offer#
海康威视公司福利 1137人发布