类似的翻转整段链表,这里要用到其中的思路:
https://blog.csdn.net/qq_52934831/article/details/119703230
地址:
https://leetcode-cn.com/problems/reverse-linked-list-ii/
描述:
思路:
代码:
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution {
public:
ListNode* reverseBetween(ListNode* head, int left, int right) {
//尽量扫描一遍完成翻转
//节点数目一定大于0,1<=left<=right<=n
if(head->next==NULL) return head;
ListNode *dummy =new ListNode (0,head);
ListNode *before=dummy;
for(int i=0;i<left-1;i++) before=before->next;
ListNode *a=before->next;
ListNode *after=a;
ListNode *b=a->next;
int temp=right-left;
while(temp>0){
ListNode *c=b->next;
b->next=a;
a=b;
b=c;
temp--;
}
before->next=a;
after->next=b;
return dummy->next;
}
};