题解 | #链表内指定区间反转#
链表内指定区间反转
https://www.nowcoder.com/practice/b58434e200a648c589ca2063f1faf58c
/**
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
class Solution {
public:
/**
*
* @param head ListNode类
* @param m int整型
* @param n int整型
* @return ListNode类
*/
ListNode* reverseBetween(ListNode* head, int m, int n)
{
ListNode* res=new ListNode(1);
ListNode* pre_m=res;
ListNode* cur=head;
ListNode* res_tail=res;
for(int i=1;cur!=NULL;i++)
{
ListNode* p=new ListNode(1);
p->val=cur->val;
p->next=NULL;
if(i<m)
{
res_tail->next=p;
res_tail=p;
pre_m=pre_m->next;
}
//位序小于等于m,尾插
else if(i==m||i>n)
{
res_tail->next=p;
res_tail=p;
}
//位序大于n,尾插
else if(i<=n)
{
p->next=pre_m->next;
pre_m->next=p;
cout<<pre_m->next->val;
}//位序大于m小于等于n,插在第m个位置
cur=cur->next;
}
return res->next;
}
};
查看8道真题和解析