###Reverse list
反转list,使用递归方式
如图所示,h为已经经过递归反转过的链表头,在递归之前保存的q指针已经是反转之后的尾指针,修改p指针为新的尾节点,返回h节点
###Code
struct ListNode
{
int val;
ListNode* next;
ListNode(int v):val(v),next(nullptr){}
};
ListNode* reverseListRecur(ListNode* head)
{
if(head == nullptr)
{
return head;
}
ListNode* p = head;
ListNode* q = head->next;
if(q == nullptr)
{
return head;
}
ListNode* newHead = reverseListRecur(p->next);
q->next = p;
p->next = nullptr;
return newHead;
}