92. Reverse Linked List II
做没有头结点的链表题,先造个头结点贼方便,屡试不爽。
class Solution {
public:
ListNode* reverseBetween(ListNode* head, int m, int n) {
if (m == n) return head;
ListNode *p = new ListNode(0);
p->next = head;
head = p;
ListNode *left = head, *right = head, *q = head;
int i = 0;
while (q) {
if (i == m - 1) {
left = q;
right = q->next;
q = q->next;
} else if (i > m && i < n) {
p = q->next;
q->next = left->next;
left->next = q;
q = p;
} else if (i == n) {
right->next = q->next;
q->next = left->next;
left->next = q;
q = right->next;
} else if (i > n) break;
else q = q->next;
i++;
}
return head->next;
}
};