LeetCode 92. 反转链表 II
原题链接
中等
作者:
未名湖畔的梦
,
2021-03-29 11:56:45
,
所有人可见
,
阅读 275
class Solution {
public:
ListNode* reverseBetween(ListNode* head, int m, int n) {
if (!head || !head->next) return head;
ListNode *dummy = new ListNode(0), *p = dummy;
dummy->next = head;
for (int i = 1; i <= m - 1; ++i)
p = p->next;
ListNode *mid = p;
for (int i = 1; i <= n - m + 1; ++i) mid = mid->next;
ListNode *post = mid->next;
mid->next = nullptr;
mid = p->next;
p->next = reverseList(p->next);
mid->next = post;
p = dummy->next;
delete dummy; dummy = nullptr;
return p;
}
// 翻转链表
ListNode *reverseList(ListNode *head){
if (!head || !head->next) return head;
ListNode *pre = nullptr, *cur = head, *post = nullptr;
while (cur){
post = cur->next;
cur->next = pre;
pre = cur;
cur = post;
}
return pre;
}
};