I've written the following code for sorting a singly linked list using bubble sort. Sorting procedure should sort the nodes of the list on the basis of the data they contain. Sorting the nodes only exchanging the data among them won't be accepted. My code triggers a segmentation fault (core dumped). I think I'm not tracking the head pointer correctly. I'm sharing the full code for the reproduction of results.
#include<iostream>
using namespace std;
typedef struct node
{
int data;
struct node *next;
} node;
node* create_node(node *head, int data)
{
node *baby = (node*)malloc(sizeof(node));
baby->data = data;
baby->next = NULL;
if(head==NULL)
head = baby;
else
{
node *curr = head;
while(curr->next != NULL)
curr = curr->next;
curr->next = baby;
}
return head;
}
void sort_bubble(node *head)
{
int count=0, i, j, temp;
bool swapped;
node *curr, *tempo, *p1, *p2;
for(curr=head; curr!=NULL; curr=curr->next)
count = count+1;
for(i=0; i<=(count-2); i++)
{
curr = head;
swapped = false;
for(j=0; j<=(count-2-i); j++)
{
p1 = curr;
p2 = p1->next;
if(p1->data > p2->data)
{
tempo = p2->next;
p2->next = p1;
p1->next = tempo;
curr = p2;
swapped = true;
}
curr = curr->next;
}
if(swapped = false)
break;
}
}
void print_list(node *head)
{
node *curr = head;
while(curr)
{
cout<<curr->data<<" ";
curr = curr->next;
}
cout<<"\n";
}
int main()
{
int count = 6;
node *head = NULL;
head = create_node(head, 40);
head = create_node(head, 10);
head = create_node(head, 60);
head = create_node(head, 50);
head = create_node(head, 20);
head = create_node(head, 30);
print_list(head);
sort_bubble(head);
print_list(head);
return 0;
}
curr = p2is?std::sort?head = create_node(head, 30);removes the crash? Did you identify which line crashes? (You should.) If it's crashing insort_bubblethen there's no need to callprint_list()afterwards (in the code for this question) since execution never gets there.