Pointers C Linkedlist Adding Always NULL -
i've written function adding end of singly linked list in c. don't why if head element null, why continues remaining null after successive adds.
the struct defined this:
typedef struct node* node; struct node { int data; node next; }
in main have this:
node test = null; add(test,1); add(test,2); add(test,3);
function add defined such:
void add(node head, int newdata) { node n = createnode(newdata); if (head==null) { head = n; return; } else { node tmp = head; while (tmp->next != null) { tmp = tmp->next; } tmp = n; } }
createnode defined thus:
node createnode(int data) { node n = (node) malloc(sizeof(struct node)); n->next = null; n->data = data; return n; }
what confused that, add function works fine if first initialize head (node test = createnode(1)) , proceeds add rest of values alright. if leave test node null, doesn't add values? happening here?
write function add
following way
void add( node *head, int newdata ) { node n = createnode( newdata ); while ( *head ) head = &( *head )->next; *head = n; }
or can write following way
void add( node *head, int newdata ) { while ( *head ) head = &( *head )->next; *head = createnode( newdata ); }
and call like
node test = null; add( &test, 1 ); add( &test, 2 ); add( &test, 3 );
take account function createnode
must declared before function add
, missed semicolon in structure definition
struct node { int data; node next; } ^^^
also not idea use same identifier struture tag , pointer same structure
typedef struct node* node;
at least better write like
typedef struct node* node_ptr;
Comments
Post a Comment