单链表的就地逆置,我是个伞兵,差不多一百行才写出来。
效果图
int Exchange_HLinkList( LinkList l, int first, int second, int length )
{
//first和second分别表示待交换两段的首结点的顺序序号
int len,count, mid;
//tail1和tail2分别指向两段的尾结点
LinkList prev, tail1, tail2, temp, temp2;
//设置递归终点
if( second - first == 0 )
{
return ;
}
//求出小段长度
if( length % 2 == 0 )
{
len = second - first;
}
else
{
len = second - first - 1;
}
//使prev指向第一段前驱结点
count = 1;
if( first != 1 )
{
prev = l->next;
}
else
{
prev = l;
}
while( prev && count < first - 1 )
{
prev = prev->next;
count++;
}
//使tail1指向第一段尾结点
count = 1;
tail1 = prev->next;
while( tail1 && count < len )
{
tail1 = tail1->next;
count++;
}
//是tail2指向第二段尾结点
count = 1;
tail2 = tail1;
if( length % 2 == 0 )
{
while( tail2 && count < len + 1 )
{
tail2 = tail2->next;
count++;
}
}
else
{
while( tail2 && count < len + 2 )
{
tail2 = tail2->next;
count++;
}
}
//交换两段
if( length % 2 == 0 )
{
temp = prev->next;
prev->next = tail1->next;
tail1->next = tail2->next;
tail2->next = temp;
}
else
{
temp = prev->next;
temp2 = tail1->next;
prev->next = temp2->next;
temp2->next = temp;
tail1->next = tail2->next;
tail2->next = temp2;
}
//至此位置对调完成
Display_HLinkList(l);
//递归对大段内小段进行位置对调
//递归
if( len % 2 == 0 )
{
Exchange_HLinkList( l, first, first + len / 2, len );
Exchange_HLinkList( l, second, second + len / 2, len );
}
else
{
if( len == 1 )
{
return ;
}
Exchange_HLinkList( l, first, first + len / 2 + 1, len );
Exchange_HLinkList( l, second, second + len / 2 + 1, len );
}
return 0;
}
int main()
{
LinkList head = Create_HLinkList();
/*LinkList head2 = Create_HLinkList();*/
int i,m,n;
printf("已经:%s啦!\n",__TIME__);
printf("请输入m:");
scanf("%d",&m);
fflush(stdin);
/*printf("请输入n:");
scanf("%d",&n);
fflush(stdin);*/
for( i = 1; i <= m; i++ )
{
Insert_HLinkList( head, i, i );
}
/*for( i = 1; i <= n; i++ )
{
Insert_HLinkList( head2, i, i );
}*/
printf("逆置前:\n");
Display_HLinkList(head);
/*Display_HLinkList(head2);*/
if( m % 2 == 0 )
{
Exchange_HLinkList( head, 1, m / 2 + 1, Length_HLinkList(head) );
}
else
{
Exchange_HLinkList( head, 1, m / 2 + 2, Length_HLinkList(head) );
}
printf("逆置后:\n");
Display_HLinkList(head);
free(head);
/*free(head2);*/
system("pause");
return 0;
}
写完的我已经没勇气去看大神的答案