C - Inserting into sorted linked list with double pointers -
i'm trying create sorted linked list in c following code getting segmentation fault before of input printed. believe because i'm checking ((*link)->value < val) in while loop, @ beginning, null. tried adding conditional if there no elements in list didnt work. how check see if value add smaller without getting seg. fault?
struct nodetag { int value; struct nodetag *next; }; typedef struct nodetag node; typedef struct { node *head; int length; } list; void insertsorted(list *list, int val) { node **link = &(list->head); while (*link != null || (*link)->value < val) { //move node correct place in list link = &((*link)->next); } //create new node node *n = (node *)malloc(sizeof(node)); n->value = val; //set next null n->next = null; //insert new node *link = n; }
here printlist:
void printlist( list *list ) { printf( "%d elements :", list->length ); ( node *n = list->head; n; n = n->next ) printf( " %d", n->value ); printf( "\n" ); }
input: 72 19 47 31 8 36 12 88 15 75 51 29 expected output: 8 12 15 19 29 31 36 47 51 72 75 88
here problems in code:
you use
||
instead of&&
. ifnext
membernull
, @ end of list, insert right there.the argument name
list
uselink
in bodyyou don't need cast return value of
malloc()
in c , considered counterproductive, if forget include<stdlib.h>
.you not test allocation failure
you not link rest of list inserted node.
the function should return pointer inserted node, giving caller chance check memory allocation failure.
you should not comment obvious.
here corrected version:
#include <stdlib.h> node *insertsorted(list *list, int val) { node **link = &list->head; while (*link != null && (*link)->value < val) { //skip node link = &(*link)->next; } //create new node node *n = malloc(sizeof(node)); if (n != null) { n->value = val; n->next = *link; // link rest of list *link = n; //insert new node } return n; }
Comments
Post a Comment