C++ 按升序排序链表并打印已排序的列表
我正在尝试按升序对链表进行排序,并停留在这里。代码的其余部分工作正常(追加、前置函数)。我在这里尝试使用冒泡排序算法 但是,输出显示分段错误。我在这里做错了什么C++ 按升序排序链表并打印已排序的列表,c++,linked-list,c++14,bubble-sort,C++,Linked List,C++14,Bubble Sort,我正在尝试按升序对链表进行排序,并停留在这里。代码的其余部分工作正常(追加、前置函数)。我在这里尝试使用冒泡排序算法 但是,输出显示分段错误。我在这里做错了什么 void sortLinkedList(Node** head_ref) { Node* slow_node =(*head_ref); Node* fast_node=NULL; Node* temp=NULL; while(slow_node->next!=NULL) {
void sortLinkedList(Node** head_ref)
{
Node* slow_node =(*head_ref);
Node* fast_node=NULL;
Node* temp=NULL;
while(slow_node->next!=NULL)
{
fast_node=slow_node->next;
while(fast_node->next!=NULL)
{
if(fast_node->data>fast_node->next->data)
{
temp->data=fast_node->data;
fast_node->data=fast_node->next->data;
fast_node->next->data=temp->data;
}
fast_node=fast_node->next;
}
slow_node=slow_node->next;
}
}
void printList(Node** head_ref)
{
Node* new_node=(*head_ref);
while(new_node!=NULL)
{
cout<<new_node->data<<"-->";
new_node=new_node->next;
}
cout<<"NULL";
cout<<endl;
}
int main()
{
Node* head=new Node();
head=NULL;
insertAtEnd(&head,2);
printList(&head);
insertAtEnd(&head,3);
printList(&head);
insertAtEnd(&head,2);
printList(&head);
insertAtEnd(&head,4);
printList(&head);
insertAtEnd(&head,5);
printList(&head);
cout<<"Sorted List"<<endl;
sortLinkedList(&head);
printList(&head);
}
冒泡排序的问题是交换操作。您使用temp(为NULL)并尝试访问数据元素。这会触发分段错误 在最简单的情况下,您可以使用。您的气泡排序看起来像
void sortLinkedList(Node** head_ref)
{
Node* slow_node =(*head_ref);
Node* fast_node=NULL;
while(slow_node->next!=NULL)
{
fast_node=slow_node->next;
while(fast_node->next!=NULL)
{
if(fast_node->data>fast_node->next->data)
{
std::swap(fast_node->data, fast_node->next->data);
}
fast_node=fast_node->next;
}
slow_node=slow_node->next;
}
}
你有
Node* temp=NULL;
然后你呢
temp->data=fast_node->data;
因为temp
是一个空指针,所以它会爆炸
如果您要交换节点的数据,则不需要整个节点,只需要一个data
类型的节点即可:
if(fast_node->data>fast_node->next->data)
{
whatever_data_is temp = fast_node->data;
fast_node->data = fast_node->next->data;
fast_node->next->data = temp;
}
但您的标准库中已经有一个交换函数,因此您可以简化:
if (fast_node->data>fast_node->next->data)
{
std::swap(fast_node->data, fast_node->next->data);
}
您是否尝试使用调试器运行它?节点定义在哪里?。。。您将在哪里分配给temp?将
节点**
传递给打印功能没有意义。使用const Node*
。通常,链表排序将重新指向节点,而不是交换数据。
if (fast_node->data>fast_node->next->data)
{
std::swap(fast_node->data, fast_node->next->data);
}