m=1的时候,必须要返回那个p2
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*
* C语言声明定义全局变量请加上static,防止重复定义
*/
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param head ListNode类
* @param m int整型
* @param n int整型
* @return ListNode类
*/
struct ListNode* reverseBetween(struct ListNode* head, int m, int n ) {
// write code here
struct ListNode* p0;
struct ListNode* p1;
struct ListNode* p2;
struct ListNode* pn;
p0 = head;
p1 = head;
p2 = head;
pn = NULL;
if(head == NULL || head->next ==NULL || (m==n))
{
return head;
}
else
{
for(int i=1;i<m;i++)
{
p0 = p1;
p1 = p1->next;
pn = p1;
}
for(int j=1;j<n;j++)
{
p2 = p2->next;
}
struct ListNode* cur;
struct ListNode* pre;
struct ListNode* nex;
pre = p1;
cur = pre->next;
nex = NULL;
while(pre != p2) //反转
{
nex = cur->next;
cur->next = pre;
pre = cur;
cur = nex;
}
p0->next = pre;
p1->next = cur; //首尾相连
}
if (m==1)
{
return p2;
}
return head;
}