第m个结点到第n个结点反转单链表
step1
step2
step3
代码实现
#include<stdio.h>
#include<malloc.h>
typedef struct node
{
int data;
struct node *next;
}*list;
list gen()
{
list head,end,node;
int num;
head=(list)malloc(sizeof(struct node));
end=head;
scanf("%d",&num);
while(num>=0)
{
node=(list)malloc(sizeof(struct node));
node->data=num;
end->next=node;
end=node;
scanf("%d",&num);
}
end->next=NULL;
return head;
}
list reverse(int start,int end,list head)
{
int i;
int cnt;
list temp,new,old,idx;
temp=head;
new=head;
for(i=0;i<start;i++)//step1:找到temp,old,new的位置
{
if(i<start-1)
{
temp=temp->next;
}
new=new->next;
}
old=new->next;
idx=old->next;
for(cnt=0;cnt<end-start;cnt++)
{
old->next=new;//step2依次反转
new=old;//step3移位置
old=idx;
if(idx)
idx=idx->next;
}
temp->next->next=old;//连接新头和新尾
temp->next=new;
return head;
}
void display(list head)
{
int flag=0;
while(head->next)
{
head=head->next;
if(flag==0)
{
printf("%d",head->data);
flag=1;
}
else
{
printf(" %d",head->data);
}
}
}
int main()
{
list head;
int start,end;
head=gen();
display(head);
scanf("%d%d",&start,&end);
head=reverse(start,end,head);
display(head);
return 0;
}