我编写代码是为了两两地交换链接列表中的元素,我的代码可以处理奇数的元素,但不处理偶数的元素。
输入-1->2->3->4->5->6->7
输出-2->1->4->3->6->5->7
void sort()
{
node *ptr=head;
node *ptr1=head;
int temp;
while(ptr->next!=NULL)
{
temp=(ptr->next)->info;
(ptr->next)->info=ptr->info;
ptr->info=temp;
//This statement is not working with even number of elements as
//when it reaches last element it is going beyond the list and
//I am unable to rectify how to rectify this problem
ptr=(ptr->next)->next;
}
}发布于 2015-03-29 07:03:54
不检查当前节点是否等于NULL。当节点数甚至在此语句之后
ptr=(ptr->next)->next;ptr可以等于NULL,并且不检查这个值。
该函数可以按以下方式编写
void adjacent_swap()
{
for ( node *p = head; p!= NULL && p->next != NULL; p = p->next )
{
int tmp = p->info;
p->info = p->next->info;
p = p->next;
p->info = tmp;
}
}发布于 2015-03-29 07:01:00
我认为while(ptr->next!=NULL)应该改为while (ptr!=NULL && ptr->next!=NULL)
发布于 2015-03-29 07:12:44
重用您的代码只需调整以下内容:
while(ptr->next!=NULL && ptr->next->next!=null )https://stackoverflow.com/questions/29326446
复制相似问题