题解 | #反转链表#

反转链表

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

递归法

class Solution {
public:
    ListNode* ReverseList(ListNode* pHead) {
		if(pHead==nullptr || pHead->next==nullptr){  // 这里的phead==null是为了放置上来就是空结点的情况
			return pHead;
		}
		
		ListNode *cur = ReverseList(pHead->next);
		pHead->next->next = pHead;   // 先连next
		pHead->next = nullptr;   // 再断键
		return cur;
    }

};

全部评论

相关推荐

点赞 收藏 评论
分享
牛客网
牛客企业服务