【发布时间】:2020-09-02 08:37:00
【问题描述】:
我正在尝试按升序对链接列表进行排序并停留在此处。其余代码工作正常(附加,前置函数)。我在这里尝试使用冒泡排序算法。
但是,输出显示分段错误。我在这里做错了什么?
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);
}
输出
2-->NULL
2-->3-->NULL
2-->3-->2-->NULL
2-->3-->2-->4-->NULL
2-->3-->2-->4-->5-->NULL
Sorted List
Segmentation fault (Core dumped)
【问题讨论】:
-
你试过用调试器运行它吗?
-
节点定义在哪里?
-
... 你在哪里分配 temp?
-
将
Node**传递给打印函数是没有意义的。使用const Node*。 -
通常链表排序会重新指向节点,而不是交换数据。
标签: c++ linked-list c++14 bubble-sort