方法1:
加入一个指向头节点的节点,简化操作
class Solution {
public:
ListNode* reverseBetween(ListNode* head, int m, int n) {
if(head==NULL||head->next==NULL)
return head;
ListNode* h=new ListNode(0);
h->next=head;
ListNode* pre=h;
int i;
for(i=1;i<m;i++)
pre=pre->next;
ListNode* pos=pre;
pre=pre->next;
ListNode* end=pre;
ListNode* p=pre->next;
ListNode* nx=NULL;
while(p&&i<n)
{
nx=p->next;
p->next=pre;
pre=p;
p=nx;
i++;
}
pos->next=pre;
end->next=p;
h=h->next;
return h;
}
};
方法2:链表尾插法;
class Solution {
public:
ListNode* reverseBetween(ListNode* head, int m, int n) {
if(head==NULL||head->next==NULL)
return head;
ListNode* h=new ListNode(-1);
h->next=head;
int i;
ListNode* pre=h;
for(i=1;i<m;i++)
pre=pre->next;
ListNode* tail=pre->next;
ListNode* p=NULL;
while(i<n)
{
p=tail->next;
tail->next=p->next;
p->next=pre->next;
pre->next=p;
i++;
}
return h->next;
}
};