基本思路:反转从位置 m 到 n 的链表。反转的基本操作是遍历时将节点摘下插入到链表头部,这里则是插入到反转的起始位置
1、先找到要进行反转的起始位置
2、n-m得到摘下的节点个数,要进行n-m次摘下插入操作
struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
class Solution {
public:
ListNode* reverseBetween(ListNode* head, int m, int n) {
if (head == NULL || head->next == NULL)
return head;
ListNode *L = new ListNode(0);
L->next = head;
ListNode *p = head->next, *tail = head,*q=L;
int times = n - m;
while (--m){
p = p->next;
tail = tail->next;
q = q->next;
}
while (times--){
tail->next = p->next;
p->next = q->next;
q->next = p;
p = tail->next;
}
return L->next;
}
};