给你单链表的头指针 head
和两个整数 left
和 right
,其中 left <= right
。请你反转从位置 left
到位置 right
的链表节点,返回 反转后的链表 。
示例 1:
struct ListNode* reverseBetween(struct ListNode* head, int left, int right) {
if(head == NULL)
return NULL;
if(head->next == NULL)
return head;
int newleft = left - 1,newright = right - 1;
struct ListNode* phead = head, * cur = head;
while(newleft--)
{
cur = phead;//得到反转位置开始之前的位置
phead = phead->next;
}
struct ListNode* Head = phead;
phead = head;
while(newright--)
{
phead = phead->next;
}
struct ListNode* Tail = phead;
struct ListNode* Tailnext = Tail->next;//得到反转位置最后的下一个位置
struct ListNode* n1 = NULL,*n2 = Head,*n3 = Head->next;
while(n1 != Tail)
{
n2->next = n1;
n1 = n2;
n2 = n3;
if(n3)
n3 = n3->next;
}
Head->next = Tailnext;
if( left == 1)
return n1;
cur->next = n1;
return head;
}