详细思路
链表题,别管其他的,先给我画图 画图
class Solution { public: ListNode* reverseBetween(ListNode* head, int left, int right) { ListNode*dummy=new ListNode(0,head); ListNode*pre=dummy,*L=head,*R=dummy,*nex=head; while(right--){ if(--left>0){ pre=pre->next; L=L->next; } nex=nex->next; R=R->next; } pre->next=nullptr; R->next=nullptr; myReverse(L); pre->next=R; L->next=nex; return dummy->next; } void myReverse(ListNode*pre){ if(!pre||!pre->next)return ; ListNode*cur=pre->next; pre->next=nullptr; while(cur->next){ ListNode*nex=cur->next; cur->next=pre; pre=cur; cur=nex; } cur->next=pre; } };踩过的坑 链表题,唯有画图是唯一的方法,图的例子要长,一行代码一张图 头插法一次遍历
画图,先随便花找出方法,然后while内解决第一次和最后
class Solution { public: ListNode* reverseBetween(ListNode* head, int left, int right) { if(left==right)return head; ListNode*dummy=new ListNode(0,head); ListNode*first=dummy,*cur=head->next; for(int i=1;i<=left-1;i++){ first=first->next; cur=cur->next; } ListNode *pre=first->next; for(int i=left+1;i<=right;i++){ ListNode*prepre=first->next,*nex=cur->next; first->next=cur; pre->next=nex; cur->next=prepre; cur=nex; } return dummy->next; } };踩过的坑 常见解决头部方法:dummy