题意:反转一个list n-m之间的节点
每次遇到链表的题都得调试很久,因为很容易考虑不全面和出错。取节点的内容时候,一定要判断结点是否为NULL。同时要注意是否是从头节点开始反转,然后反转的位置,节点数和链表的关系。注意考虑全面。一般涉及链表节点间的操作都要考虑保存三个节点再考虑转向问题。下面是我的代码。
class Solution {
public:
ListNode* reverseBetween(ListNode* head, int m, int n) {
ListNode* pHead=head;
int num=n-m+1;
int s=m;
m=m-2;
while(m>0&&pHead)
{
pHead=pHead->next;
m--;
}
//如果是从头节点开始反转
ListNode*preStart=NULL;
ListNode* start=NULL;
if(s==1)
{
start=pHead;
}
else
{
preStart=pHead;
start=pHead->next;
}
//总个数小于m
if(start==NULL||num<2)
return head;
ListNode*first=NULL;
ListNode*second=NULL;
ListNode*third=NULL;
first=start;
second= (first)?first->next:NULL;
//反转这几个节点
num--;
while(num>0&&first&&second)
{
third=second->next;
second->next=first;
first=second;
second=third;
num--;
}
ListNode*end=first;
if(preStart)
preStart->next=end;
else
head=end;
start->next=second;
return head;
}
};