c - Sorting a linked list in an ascending way -
i trying write function inserts numbers(from user)to nodes (1 number each node) , sorts them in ascending way. wrote function:
void insertnode(struct n_node *head) { struct n_node *temp = head; int number; printf("please insert number node\n"); scanf("%d", &number); while (number != sentry) { while ((temp->next != null) && (temp->next->num < number)) { temp = temp->next; } struct n_node *addnode = (struct n_node*)malloc(sizeof(struct n_node)); addnode->num = number; if (temp->next == null && number < temp->num) { addnode->next = temp; head = addnode; } else { addnode->next = temp->next; temp->next = addnode; } temp = head; scanf("%d", &number); } options(); }
it compiles right after insert first number stops, gives me break message , points on line:
while ((temp->next != null) && (temp->next->num < number))
nothing appears on error list, appreciated, thanks!
in algorithm, not testing special cases in correct order:
- if list empty,
head
null
, testtemp->next != null
invokes undefined behaviour. - if number smaller number in first node, there no need try , iterate on list, node needs inserted @ head.
you should first allocate new node , check special cases single test:
struct n_node *addnode = malloc(sizeof(struct n_node)); addnode->num = number; if (head == null || number < head->num) { addnode->next = head; head = addnode; }
otherwise, iteration loop correct , node inserted after temp
when reach false condition:
while (temp->next != null && temp->next->num < number) { temp = temp->next; } addnode->next = temp->next; temp->next = addnode;
the loop becomes simpler:
void insertnode(struct n_node **headp) { struct n_node *head = *headp; int number; printf("please insert number node\n"); while (scanf("%d", &number) == 1 && number != sentry) { struct n_node *addnode = malloc(sizeof(struct n_node)); if (addnode == null) { printf("out of memory\n"); return; } addnode->num = number; if (head == null || number < head->num) { addnode->next = head; *headp = head = addnode; } else { struct n_node *temp = head; while (temp->next != null && temp->next->num < number) { temp = temp->next; } addnode->next = temp->next; temp->next = addnode; } } options(); // head not passed function? }
also note change in api allow function update list head in caller's scope, change stop scanning numbers upon end of file or non number input in addition magic number.
Comments
Post a Comment