<span style="font-size:14px;">这一道题,最好先做之前的 Reverse Linked ListI</span>
之后把他分成几个节点
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
int LengthList(struct ListNode* head)
{
if(head==NULL)
return 0;
int length=0;
struct ListNode* pCurrent=head;
while(pCurrent!=NULL)
{
length++;
pCurrent=pCurrent->next;
}
//free(pCurrent);
return length;
}
struct ListNode* reverseList(struct ListNode* head) {
struct ListNode* newhead;
newhead=NULL;
//这样就不需要翻转了
if (head==NULL||head->next==NULL)
{
return head;
}
struct ListNode* pCurrent=head; //一样的点
while(pCurrent!=NULL)
{
struct ListNode* tmp=pCurrent;
pCurrent=pCurrent->next;
tmp->next=newhead; //把节点放在节点前面,插入到链表的最前端
newhead=tmp;
}
return newhead;
}
struct ListNode* reverseBetween(struct ListNode* head, int m, int n)
{
int length;
struct ListNode* pCurrent=head;
length=LengthList(pCurrent);
int diff=n-m;
if (diff==0)
{
return head;
}
if (m==1)
{
if (length==n)
{
head=reverseList(head);
return head;
}
if (n<length)
{
pCurrent=head;
while (diff--) //
{
pCurrent=pCurrent->next;
}
struct ListNode* pCurrentNhead;
pCurrentNhead=pCurrent->next;
struct ListNode* pCurrentMTail=pCurrent;
pCurrent->next=NULL; //first tail node.
head=reverseList(head);
pCurrent=head;
while(pCurrent->next!=NULL) //走到反转的地方n头结点的前面.. //另外一种方法m都头结点已经算是尾节点了。
{
pCurrent=pCurrent->next;
}
pCurrent->next=pCurrentNhead;
return head;
}
}
else
{
if (length==n)
{
struct ListNode* pCurrentHeadTail=head;
pCurrent=head;
m--;
while(m--)
{
pCurrentHeadTail=pCurrent;
pCurrent=pCurrent->next;
}
//分段
pCurrentHeadTail->next=NULL;
struct ListNode* pCurrentHeadm=pCurrent;
pCurrent=pCurrentHeadm;
pCurrentHeadm=reverseList(pCurrentHeadm);
pCurrentHeadTail->next=pCurrentHeadm;
return head;
}
if (n<length)
{
struct ListNode* pCurrentHeadTail=head;
pCurrent=head;
m--;
while(m--)
{
pCurrentHeadTail=pCurrent;
pCurrent=pCurrent->next;
}
//分段
pCurrentHeadTail->next=NULL;
struct ListNode* pCurrentHeadm=pCurrent;
while (diff--)
{
pCurrent=pCurrent->next;
}
struct ListNode* pCurrentNhead;
pCurrentNhead=pCurrent->next;
struct ListNode* pCurrentMTail=pCurrent;
pCurrent->next=NULL;
pCurrentMTail=pCurrentHeadm;
pCurrentHeadm=reverseList(pCurrentHeadm);
pCurrentHeadTail->next=pCurrentHeadm;
pCurrentMTail->next=pCurrentNhead;
return head;
}
}
}