按升序对链表进行排序,并打印排序后的列表



我正在尝试按升序对链表进行排序,但一直停留在这里。其余的代码运行良好(追加、预处理函数(。我试着在这里使用冒泡排序算法。

但是,输出显示分段错误。我在这里做错了什么?

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)

您有

Node* temp=NULL;

然后你的

temp->data=fast_node->data;

并且由于CCD_ 1是空指针而变为BOOM。

如果你要交换节点的数据,你不需要一个完整的节点,只需要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为NULL,并尝试访问数据元素。这会触发分段故障。

在最简单的情况下,您可以使用std::swap。你的气泡排序看起来像

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;
}
}

最新更新