How to insert string into linked list in c -
i want write function can insert string alphabetically. can declared as;
typedef struct node node; typedef struct node { char *data; node *next; }; node *insertion(node *head,char *arr); how can define function?
my codes;
#include <stdio.h> #include <stdlib.h> #include <string.h> typedef struct node node; typedef struct node { char *data; node *next; }; node *mylist = 0; void addword(char *word) // add new word list mylist { node *item,*next; item = (node *) malloc(sizeof(node)); if ( item==0 ) { printf ("malloc failed \n"); return ; } strcpy(item->data,word); // copy word new item item->next = 0; // set next item nothing if ( mylist == 0 ) // if list empty, make first item { mylist = item; return ; } if(strcmp(word,mylist->data) < 0 ) // check if new item comes before first item in old list { item->next = mylist; mylist = item; return ; } // check see if item inserted before next item ( next = mylist ; next ->next != 0 ; next = next ->next ) { if (strcmp (word, next->next->data) < 0 ) { // insert item before next item. item ->next = next->next; next->next = item ; return; } } // there no more items ! add end next ->next = item; }
item = (node *) malloc(sizeof(node)); if ( item==0 ) { printf ("malloc failed \n"); return ; } strcpy(item->data,word); // copy word new item item->data non-initialized pointer. should either allocate space copy into, or declare data array in node structure:
char data[somesize];
Comments
Post a Comment