思路:
1.创建新链表读取不需要反转的node---prev=prev->next
2.指针到达反转位置后对该区域进行直接反转
for(int i=m;i<n;i++)
{
prev->next=cur->next;
cur->next=head2->next;
head2->next=cur;
cur=prev->next;
}
3.输出 dummu.next
代码:
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* reverseBetween(ListNode* head, int m, int n) {
//ListNode* pre=NULL;
//ListNode* cur=head;
ListNode dummy(-1);
ListNode *prev=&dummy;
dummy.next=head;
for(int i=1;i<m;++i)
{
prev=prev->next;
}
//指针到达反转位置
ListNode* const head2=prev;
prev=head2->next;
ListNode* cur=prev->next;
for(int i=m;i<n;++i)
{
prev->next=cur->next;
cur->next=head2->next;
head2->next=cur;
cur=prev->next;
}
return dummy.next;
}
};
方法二:
class Solution {
public:
ListNode* reverseBetween(ListNode* head, int m, int n) {
if(m==n) return head;
auto dummy=new ListNode(-1);
dummy->next=head;
auto a=dummy,d=dummy;
for(int i=0;i<m-1;i++) a=a->next;
for(int i=0;i<n;i++) d=d->next;
auto b=a->next,c=d->next;
for(auto p=b,q=b->next;q!=c;) //区间内翻转
{
auto o=q->next;
q->next=p;
p=q;
q=o;
}
b->next=c;
a->next=d;
return dummy->next;
}
};
Every step of barefoot running deserves to be recorded