题解 | #链表内指定区间反转#
链表内指定区间反转
https://www.nowcoder.com/practice/b58434e200a648c589ca2063f1faf58c
/**
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param head ListNode类
* @param m int整型
* @param n int整型
* @return ListNode类
*/
#include <math.h>
#include <stddef.h>
struct ListNode* reverseBetween(struct ListNode* head, int m, int n ) {
// write code here
struct ListNode* new_head=(struct ListNode*)malloc(sizeof(struct ListNode));
new_head->next = head;
struct ListNode* p1=new_head;
struct ListNode* p2=NULL;
struct ListNode* p3=NULL;
struct ListNode* p4=NULL;
struct ListNode* cur=NULL;
struct ListNode* pre=NULL;
struct ListNode* next=NULL;
//1->2->3->4->5
//p1 p2 p3 p4
//首先遍历一遍链表找到这四个点,然后将p2到p3这块反转,再重定向p1->next=p3;p2->next=p4;
//结束
int i=0;
for(i = 0;i < m-1;i++)
{
p1=p1->next;
}
p2=p1->next;
p3=p2;
for(i=0;i<n-m;i++)
{
p3=p3->next;
}
p4=p3->next;
//从p2开始反转
cur=p2;
for(i=0;i<n-m+1;i++)
{
next=cur->next;
cur->next=pre;
pre=cur;
cur=next;
}
p1->next=p3;
if(p4 != NULL)
{
p2->next=p4;
}
//printf("p1,p2,p3,p4->val is %d %d %d %d\n",p1->val,p2->val,p3->val,p4->val);
return new_head->next;
}
科大讯飞公司氛围 474人发布