c 语言链表冒泡排序,出错了,求原因

2023-01-07 23:06

2023-01-07 23:38
int sort_ID(STU *head,int len){
int i,j;
if(len < 2)
return 0;
STU *pre = head; //前一节点
STU *cur = head->next; //交换的节点
STU *tail = cur->next; //交换的节点
for(i=1;ifor(j=0;jif(strcmp(cur->ID,tail->ID) > 0){
pre->next = tail; //交换
cur->next = tail->next;
tail->next = cur;

pre = tail; //交换成功后移
tail = cur->next;
}else{
pre = cur; //未交换平移
cur = tail;
tail = tail->next;
}
}
//重新下一轮查找
pre = head; //前一节点
cur = head->next; //交换的节点
tail = cur->next; //交换的节点

}
return 0;
}
更多回答
你这个冒泡只虽然是两次循环,但做的工作还是只有一次循环交换;
因为你的循环中,外层执行一次后,你的指针就已经指向尾部了(下次循环时,指针并没有重新指向头)。此时,如果你循环里有判断尾结点了tail->next是否为NULL,就会发现问题。你实际代码中没有判断已经很危险了。
建议楼主好好调试一下运行过程。