Home > Blockchain >  C str - Arrangement
C str - Arrangement

Time:11-30

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:

  1. Missing headers.
  2. Syntax error at printf() due to missing ;.
  3. As @HymnsForDisco said, your program segfaults when it tries to dereference a NULL pointer when head is NULL.
  4. insert() doesn't do the right thing if node being added should be the new root.
  5. (refactor) for-loop is a better fit than while-loop. Either option is correct.
  6. (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
  • Related