/**
* 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) {
if(!head || !head->next) return head;
ListNode* first=new ListNode(0);
first->next=head;
int cnt=1;
while(cnt<m){
first=first->next;
++cnt;
}
ListNode* old_pre=first;
ListNode* cur=first->next;
ListNode* cur_next=cur->next;
ListNode* new_pre=cur;
ListNode* cur_next_next;
while(cur && cnt<n)
{
cur_next_next=cur_next->next;
cur_next->next=cur;
cur=cur_next;
cur_next=cur_next_next;
++cnt;
}
old_pre->next=cur;
new_pre->next=cur_next;
/*当m==1时,此时的第一个结点就变成了最后一个反转结点
当m!=1时,就返回原先的头结点即可*/
return m==1?cur:head;
}
};
92. 反转链表 II/C++
最新推荐文章于 2022-07-29 17:38:52 发布