I have a linked list, and I want to sort them by names
(for example the names “Bx”, “Tx”, “Ax” would become : “Ax”, “Bx”, “Tx”)…
I need to switch the names if the one in the node’s right has a “smaller name”..
this is what I wrote:
typedef struct data
{
char *name;
}data;
typedef struct Node
{
data NodeData;
struct Node *next;
struct Node *prev;
}Node;
void Sorting(Node *head)
{
Node *temp = head;
Node *temp2 = (Node*)malloc(sizeof(Node));
while (temp != NULL)
{
if (1 == (strcmp(temp -> NodeData.name, temp -> next -> NodeData.name)))
{
strcpy (temp2 -> NodeData.name, temp -> NodeData.name);
strcpy (temp -> NodeData.name, temp -> next -> NodeData.name);
strcpy (temp -> next -> NodeData.name, temp2 -> NodeData.name);
}
temp = temp -> next;
}
}
I’m getting an runtime – error on the part where I need to swarp betwen the node’s name(the strcpy lines):
An access violation (segmentation fault)…
When this line is executed, there is no guarantee that temp->next is not NULL.
If it is NULL, temp->next->NodeData.Name would be rather painfull.
Also, as has been said, testing strcmp()s result against 1 is not right. strcmp can resutning any value equal to zero, < zero or > zero.
Also, as has been said, strcpy() is not right; the strings could have different allocated sizes, or could live in non-writable memory (string constants) . Swapping the pointers will suffice.
UPDATE:
BTW: bubble sorting a linked list is really ugly. Linked lists are easyer and more elagantly sorted by mergesort.