题解 | #反转链表#

反转链表

https://www.nowcoder.com/practice/75e878df47f24fdc9dc3e400ec6058ca

递归的思路

递归出口

翻转最后要将末尾节点视作头节点,一直递归到head->next == nullptr,保存末尾节点。同时如果链表为空直接return。

递归回溯

从末尾-1节点开始回溯时,需要将末尾节点的next指向前一节点,即pHead->next->next = pHead 为了避免形成循环链表们需要将pHead->next == nullptr。

时间复杂度计算

时间复杂度o(n) 遍历整个链表 空间复杂度o(n) 递归栈的内存使用

class Solution {
public:
    ListNode* ReverseList(ListNode* pHead) {
		if(pHead == nullptr || pHead->next == nullptr){ 
			return pHead;
		}
		ListNode* newList = ReverseList(pHead->next);
		pHead->next->next = pHead;
		pHead->next = nullptr;
		return newList;
    }
};
全部评论

相关推荐

评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务