gpt4 book ai didi

c - 链接功能不会按预期将最大项目放在列表的末尾

转载 作者:太空宇宙 更新时间:2023-11-04 04:27:48 25 4
gpt4 key购买 nike

我有一个链表,我必须确保无论链表的最大数目是多少,我都将它放在链表的末尾。我不确定我做错了什么。有人可以解释一下吗?

void moveAllMaxAtEnd(list A) {
int max=0;
link tmp=A->first;
link curr=tmp->next;
int i,count=0;
while(curr!=NULL){ //This first while is where I find the max item
if(curr->item>=max){
max=curr->item;
count++;
}
else{
curr=curr->next;
}
}
link prev=A->first;
link curr1=prev->next;
link tmp1;
while(curr1->next!=NULL){ //In this loop I am trying to put the
if(curr1->item==max){ //max items at the end.
prev->next=curr1->next;
tmp1=prev->next;
prev->next=curr1->next;
curr1->next=tmp1;
}
else{
prev=prev->next;
curr1=curr1->next;
}
}

}

最佳答案

虽然我还没有测试过,但它应该可以工作。如果是作业,请不要看今天的答案(自己学习会更有帮助!)。

对您的列表元素进行一些绘制并查看链接行为。您会立即发现此方法的问题。

我的绘图示例

list drawing

更正(请勿立即阅读)

void moveAllMaxAtEnd(list A) {
int max=0;
link tmp=A->first;
link curr=tmp->next;
int i,count=0;
while(curr!=NULL){ //This first while is where I find the max item
if(curr->item>=max){
max=curr->item;
count++; //not used, may be cleaned up
}
//else{ //else is not needed the code would be executed in next loop anyway
curr=curr->next;
//}
}
link prev=A->first;
link curr1=prev->next;
link tmp1;
while(curr1->next!=NULL){ //In this loop I am trying to put the
if(curr1->item==max){ //max items at the end.
prev->next=curr1->next;
tmp1=curr1; // not prev->next;
// prev->next=curr1->next; cur1 has not changed you re-do exactly the same
// curr1->next=tmp1;
curr1->next=NULL; //it will be the last element
}
else{
prev=prev->next;
curr1=curr1->next;
}
}
curr1->next = tmp1; //add the element we cut before
}

关于c - 链接功能不会按预期将最大项目放在列表的末尾,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39810008/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com