思路:指定范围内的链表反转,先找到开始反转的起始节点,然后做n - m次反转,注意边界条件m = 1的情况。
code:
class Solution {
public:
ListNode *reverseBetween(ListNode *head, int m, int n) {
ListNode * first, *last, *p = head, *q=head, *t;
int num = n - m, start = m;
while(--m){//找到开始反转的起始节点
q = p;
p = p->next;
}
first = q;
last = p;
t = p->next;
while(num--){//一共做num次反转
q = t;
t = t->next;
q->next = p;
p = q;
}
first->next = p;
last->next = t;
if(start == 1)
head = p;
return head;
}
};