没加首元结点需要考虑各种边界条件(放弃了) 使用首元结点避免内存泄漏
/**
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
class Solution {
public:
ListNode* reverseBetween(ListNode* head, int m, int n) {
if (head->next == nullptr || m == n) { // 不用翻转的情况
return head;
}
// 使用首元结点避免各种边界情况
ListNode *head_node = new ListNode(-1);
head_node->next = head;
ListNode *tmp, *pre, *cur, *nex;
tmp = pre = cur = nex = head_node;
for (int i = 1; i < m; i++) {
tmp = tmp->next;
}
pre = tmp->next;
cur = pre->next;
nex = cur->next;
for (int i = m; i < n - 1; i++) { // 第n个结点特殊处理,cur指向结点n
cur->next = pre;
pre = cur;
cur = nex;
nex = nex->next;
}
cur->next = pre;
tmp->next->next = nex;
tmp->next = cur;
head = head_node->next;
delete(head_node);
return head;
}
};