【发布时间】:2020-09-26 16:09:32
【问题描述】:
我尝试在单链表上实现冒泡排序(通过更改指针)。我想知道这个解决方案有什么问题。这似乎很清楚并且应该可以工作,但我是 C++ 的初学者,所以我想我在某个地方犯了我无法发现的错误。下面是代码:
#include <iostream>
using namespace std;
struct node{
int value;
node *next = nullptr;
};
void print(node* n){
while(n){
cout<< n->value << " ";
n = n->next;
}
cout << endl;
}
void replace(node*& first, node* second){
node* tmp = second->next;
second->next = first;
first->next = tmp;
first = second;
}
void bubbleSortRecu(node*& head, int length){
if(!head || !head->next || length == 1) return;
node* n = head;
int counter = length - 1;
while(n->next && counter){
if(n->value > n->next->value)
// std::swap(n->value, n->next->value); // swaping values works fine
replace(n, n->next);
n = n->next;
counter --;
}
bubbleSortRecu(head, --length);
}
int main(){
node* list = new node{4};
list->next = new node{3};
list->next->next = new node{5};
list->next->next->next = new node{1};
list->next->next->next->next = new node{0};
cout << "Original: ";
print(list);
cout << "Replaced: ";
replace(list, list->next);
replace(list->next->next->next, list->next->next->next->next);
print(list);
bubbleSortRecu(list, 5);
cout << "After bubblesort: ";
print(list);
return 0;
}
我已经在列表的前两个和最后两个元素上测试了替换功能。有效。致电bubbleSortRecu(list, 5) 后,我的清单已损坏。这是输出:
Original: 4 3 5 1 0
Replaced: 3 4 5 0 1
After bubblesort: 3 4 5
您能解释一下如何解决它以及我在哪里做错了吗?
【问题讨论】:
-
您是否使用调试器查看出了什么问题?
-
或者确实,如果您不想使用调试器,那么绝对经典的“在每一行上添加一个打印语句来说明上一行的结果是什么以及下一行将做什么”应该也可以工作。
-
如果 cout 方法没有帮助,可能是时候获取一个调试器,比如 Visual Studio 中的调试器,您可以一次单步执行 1 行代码,查看每个步骤的变量和流程了解为什么您的算法没有达到您的预期。
-
如果你提供一个工作示例会更容易帮助你
-
@Ethr 公平地说,使用打印语句的建议是非常糟糕的建议。您基本上花费了大量的手动工作来复制调试器已经自动执行的操作并进行更多控制。相反,花时间学习如何使用您的调试器(应该不会花很长时间)。
标签: c++ algorithm sorting bubble-sort