方法一:左右指针以及首尾指针
左右指针在交换时记录左右位置,而首尾指针记录反转界限位置。
注意:存在换头时,需要单独进行处理。
例子:
1(pre)->{2->3->4->5->6}->7(pos)->8
其中,{...}内为交换部分。
list_node * reverse_list(list_node * head,int n, int L, int R)
{
//////在下面完成代码 from L;to R
bool isRightEx = (L<=R) && (L>=1) && (R<=n);
if(isRightEx){
list_node* cur=head;
int count=1;
/* 存在换头时,cur所指向的为交换部分第一个;反之,cur指向的为pre */
while( (count+1)!=L && count!=L ){
count++;
cur=cur->next;
}
list_node* pre = cur;
list_node* left=NULL;
/* 换头时,需要处理count */
if(L==1)
count--;
else
cur=cur->next;
while((++count)<=R){
list_node* right = cur->next;
cur->next=left;
left=cur;
cur=right;
}
list_node* pos=cur;
/* 如果需要换头,则最后需要将head换掉;否则,不需要换头 */
if(L==1){
pre->next=pos;
head=left;
}else{
pre->next->next=pos;
pre->next=left;
}
}
return head;
}

京公网安备 11010502036488号