【发布时间】:2021-12-31 17:49:23
【问题描述】:
我尝试使用冒泡排序算法对链表进行排序,但最后一个节点似乎未在列表中排序。列表中的每个元素都可以排序,但最后一个除外。谁能建议我在哪里做错了以及如何解决?非常感谢! (抱歉英语不好),这是我的代码:
struct Node{
int data;
Node *next;
};
bool isEmpty(Node *head){
if (head == NULL){
return true;
}
else{
return false;
}
}
void insertAsFirstElement(Node *&head, Node *&last, int number){
Node *temp = new Node;
temp -> data = number;
temp -> next = NULL;
head = temp;
last = temp;
}
void insert(Node *&head, Node *&last, int number){
if (isEmpty(head)){
insertAsFirstElement(head , last , number);
}
else{
Node *temp = new Node;
temp->data = number;
temp->next = NULL;
last->next = temp;
last = temp;
}
}
void BubleSort(Node *&head){
struct Node *i ,*j;
int num;
for (i = head; i-> next != NULL;i=i->next){
for (j = i->next; j->next != NULL; j = j->next){
if (i->data > j-> data){
num = j->data;
j->data = i->data;
i->data = num;
}
}
}
}
void display(Node *current){
if (current == NULL){
cout<<"Nothing to display ";
}
while(current!= NULL){
cout<<current -> data<<"-> ";
current = current -> next;
}
}
int main(){
Node *head = NULL;
Node *last = NULL;
int T;cin>>T;
for (int i=0 ;i<T;i++){
int number;cin>>number;
insert(head,last,number);
}
BubleSort(head);
display(head);
}
输入:
6
1 7 4 6 9 3
输出:
1-> 4-> 6-> 7-> 9-> 3->
【问题讨论】:
-
i-> next != NULL在到达最后一个元素时退出循环。 -
我也会推荐实际的 C++,而不是 C-with-cout。我还要指出,对链表进行排序是一项愚蠢的工作。
-
您已将最后一个元素确定为问题案例;这很好。接下来,简化 - 获得尽可能短的列表,该列表可以未排序(至少 2 个元素)并且具有最后一个元素(至少 1 个元素)。也就是说,使用 2 元素列表进行调试。这种情况很简单,您应该能够手动浏览您的代码(如果有帮助,请绘制图片),但如果您愿意,可以使用调试器。当你单步执行你的代码时,寻找为什么你从来没有点击过你的
if语句。 (为什么你的内部循环的迭代次数为零?)
标签: c++ algorithm bubble-sort