题解 | #链表内指定区间反转#
链表内指定区间反转
https://www.nowcoder.com/practice/b58434e200a648c589ca2063f1faf58c
/**
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param head ListNode类
* @param m int整型
* @param n int整型
* @return ListNode类
*/
typedef struct ListNode listnode;
listnode*Buynode(int x)//获取新创建的链表节点空间
{
listnode*newnode = (listnode*)malloc(sizeof(listnode));
newnode->val = x;
newnode->next = NULL;
return newnode;
}
void ListnodePop(listnode**phead,int x)//将数据头插到新链表中
{
listnode*newnode = Buynode(x);
newnode->next = *phead;
*phead = newnode;
}
struct ListNode* reverseBetween(struct ListNode* head, int m, int n ) {
if(m==n)
{
return head;
}
listnode*l1,*l2,*l3;
l1 = head;
int count = 0;
listnode*st = NULL;
while(l1)
{
++count;
if(count==n)//获取n位置的结点地址
{
if(l1->next!=NULL)
l3 = l1->next;
else if(l1->next ==NULL)
l3 = l1;
}
if(count>=m &&count <=n)//循环头插
{
ListnodePop(&st,l1->val);
}
if(count==m-1)
{
l2 = l1;//获取m结点的前驱结点的地址
}
l1 = l1->next;
}
listnode*ptail = st;
while(ptail->next)
{
ptail = ptail->next;
}
if(count>=n &&m==1)
{
if(count==n)
{
return st;
}
ptail->next = l3;
return st;
}
else if(count>=n &&m>1)
{
l2->next = st;
if(count==n)
{
return head;
}
ptail->next = l3;
return head;
}
return head;
}
查看10道真题和解析
