Search code examples
c++linked-listc++14bubble-sort

Sorting a Linked List in ascending order and printing sorted List


I am trying to sort a linked list in ascending order and stuck at this point here. THe rest of the code is working fine (appending, prepending functions). I was trying to use the bubble sort algorithm here.

However, the output shows segmentation fault. What am I doing wrong over here?

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

}

Output

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)

Solution

  • You have

    Node* temp=NULL;
    

    and then you

    temp->data=fast_node->data;
    

    and it goes BOOM because temp is a null pointer.

    If you're going to swap the nodes' data, you don't need a whole node, just one of whatever type data is:

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

    but there already is a swapping function in your standard library, so you can simplify:

     if (fast_node->data>fast_node->next->data)
     {
         std::swap(fast_node->data, fast_node->next->data);
     }