singly linked list - Link another structure in C -
i trying data stucture in c. connect structure structure. this:
struct room { int roomnumber; struct room * nextroom; struct person * personlist; }*top=null,*temp=null,top1; struct person { int personnumber; struct person *next; }*node=null,temp1;
struct room has pointer struct person. having hard time on connecting struct. correct?
here function
void insert() { int val; printf("enter value: "); scanf("%d",&val); newnode=create_node(val); if(top->personlist==null) { top->personlist=newnode; } else { node->next=newnode; node=newnode; } }
insert person room. room created already. create_node()
1 malloc()
here's version doesn't use globals, makes functions more general , reusable:
#include <stddef.h> #include <stdlib.h> #include <stdio.h> typedef struct person { int personnumber; struct person *next; } person; /* note: typedef, not global declaration did */ typedef struct room { int roomnumber; person *personlist; person *lastinlist; struct room *nextroom; } room; /* note: typedef, not global declaration did */ person *create_person(int val) { person *ret = calloc(1, sizeof(*ret)); if (ret) { ret->personnumber = val; ret->next = null; } return ret; } int room_insert(room *r, int val) { person *p = create_person(val); if (null == p) return -1; if (null != r->personlist) r->lastinlist->next = p; else r->personlist = p; r->lastinlist = p; return 0; } int main(int argc, char **argv) { room my_room = { 0 }; /* important! initializes pointers null */ room my_other_room = { 0 }; /* important! initializes pointers null */ person *p; room_insert(&my_room, 5); room_insert(&my_other_room, -5); room_insert(&my_room, 10); room_insert(&my_other_room, -10); room_insert(&my_room, 15); room_insert(&my_other_room, -15); (p = my_room.personlist; p; p = p->next) printf("%d\n", p->personnumber); (p = my_other_room.personlist; p; p = p->next) printf("%d\n", p->personnumber); return 0; }
Comments
Post a Comment