class Solution {
public:
/**
*
* @param head ListNode类
* @param m int整型
* @param n int整型
* @return ListNode类
*/
ListNode* reverseBetween(ListNode* head, int m, int n) {
// write code here
if(head == NULL || head->next == NULL) return head;
if(m==n)return head;
//解决头节点也要反转情况
ListNode* h=(struct ListNode*)malloc(sizeof(ListNode));
h->next=head;
ListNode* p=h;
ListNode* q=h;
//m-1
for(int i=1;i<m;i++)p=p->next;
//n
for(int i=1;i<=n;i++)q=q->next;
//m
ListNode* p1=p->next;
//m+1
ListNode* p2=p1->next;
//反转头尾
p->next=q;
p1->next=q->next;
//反转p2---n-1
while(p2!=q){
p=p2->next;
p2->next=p1;
p1=p2;
p2=p;
}
p2->next=p1;
return h->next;
}
};
部分区间链表反转
最新推荐文章于 2023-09-06 14:14:04 发布