What I thought was, to sort, I'd use strcmp() to compare strings, and then based on the value, insert. This is the code,
CodePudding user response:
I fixed the following issues:
- Missing headers.
- Syntax error at
printf()
due to missing;
. - As @HymnsForDisco said, your program segfaults when it tries to dereference a NULL pointer when
head
isNULL
. insert()
doesn't do the right thing if node being added should be the new root.- (refactor)
for
-loop is a better fit thanwhile
-loop. Either option is correct. - (enhancement) Added a print function to demonstrate that insert works.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct node {
char name[50];
struct node *next;
};
struct node *insert(struct node *head, const char *name) {
struct node *toinsert = malloc(sizeof(struct node));
strcpy(toinsert->name, name);
if(!head || strcmp(name, head->name) <= 0) {
toinsert->next = head;
return toinsert;
}
struct node *temp = head;
for(; temp->next && strcmp(name, temp->next->name) > 0 ; temp=temp->next);
toinsert->next = temp->next;
temp->next = toinsert;
return head;
}
void print(struct node *head) {
for(; head; head=head->next) {
printf("%s\n", head->name);
}
}
int main() {
struct node *head = insert(NULL, "B");
head = insert(head, "A");
head = insert(head, "C");
print(head);
}
and the output is:
A
B
C