题目描述:
反转从位置 m 到 n 的链表。请使用一趟扫描完成反转。说明:1 ≤ m ≤ n ≤ 链表长度。
示例:
输入: 1->2->3->4->5->NULL, m = 2, n = 4 输出: 1->4->3->2->5->NULL
思路:
先往后遍历找到需要反转的节点作为起点(count==m),然后按照剑指offer:反转链表 的思路,设置curr,pre,pNext三个指针,把m到n之间的节点反转,最后pre指向第n个节点,curr指向第n+1个节点
找到需要反转的节点时,需要用start记录下第m个节点,用preS记录下start之前一个指针,在完成节点反转后,还需要处理头尾的反转,(a)start应该要指向第n+1个节点(curr),(b)preS指向第n个节点。要特别注意,如果start=head,即m=1,此时preS=NULL,应该直接令第n个节点为新的头结点。
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* reverseBetween(ListNode* head, int m, int n) {
if(head==NULL||head->next==NULL||m<=0||n<=0||m>=n)
return head;
ListNode* pNode = head;//当前节点
ListNode* pNext=NULL;//下一节点
ListNode* pre=NULL;//前一节点
ListNode* PreS=NULL;
ListNode* start=NULL;
ListNode* curr=NULL;
int count=0;
while(pNode)
{
count++;
if(count==m)
{
start=pNode;
pre=start;
curr=start->next;
count++;
while(curr&&count<=n)
{
pNext=curr->next;
curr->next=pre;
pre=curr;
curr=pNext;
count++;
}
start->next=curr;
if(m==1)
{
head=pre;
}
else
{
PreS->next=pre;
}
}
else
{
PreS=pNode;
pNode=pNode->next;
}
}
return head;
}
};